Convert String to ASCII Code (Binary) using PHP

This article will discuss how to convert String to ASCII Code in Binary using PHP.

Based on PHP Documentation, PHP has a String Function called ord, which can convert the first byte of a string to a value between 0 and 255.

The ord() PHP function takes the first byte of String as an input parameter and returns an unsigned integer between 0 and 255 as an output.

Syntax: ord(string)

Since it only converts the first character of the String, so if you pass the full string to its parameter, the result only shows the ASCII code of the first character of the String.

<?php
   echo ord("H")."<br/>";
   echo ord("Hai")."<br/>";
?>

Output:
72
72

To convert the full-length of String, we need to access each character in the String and get the ASCII code using ord PHP function through a loop.

To do that, try to create code for the following task:

  1. Get the length of the String
  2. Get ASCII code for every single character in a String using ord PHP function through a loop
<?php
    $str = "Hello My Name is Picky";
    
    for($i = 0; $i < strlen($str); $i++){
        echo ord($str[$i])." ";
    }
?>

Output:
72 101 108 108 111 32 77 121 32 78 97 109 101 32 105 115 32 80 105 99 107 121

As seen in the code example above, the variable $str store a String “Hello My Name is Picky”.

At line 4, the loop will run until it reaches the length of the String that obtain by using strlen() PHP function.

At line 5, the $str[$i] is accessing every single character in a String using its index. For example, if you try to echo $str[1], you will get ‘e’ (without single quotes) as a result.

Still at the same line, at line 5, the ord PHP function will convert every single character passed to its parameter into ASCII code in the Binary version.

For example, the ord PHP function will convert “H” to 72, which is the ASCII Code of the uppercase h.

Conclusion

To convert a single character using PHP, we can use the ord() PHP Function. It accepts the first byte of a string and returns an unsigned integer between 0 and 255 as an output.

To convert a full-length of string we need to get the length of the String using strlen() PHP function and convert every single character using ord() PHP function through a loop.

Try our free online ASCII converter tools:

  1. String to ASCII Code Converter (in decimal)
  2. Char & Symbols to ASCII Code (in Binary) Converter
  3. ASCII Code to Char Converter