How do I convert a string to a binary array in PHP?
4 Answers
Let's say that you want to convert $stringA="Hello" to binary.
First take the first character with ord() function. This will give you the ASCII value of the character which is decimal. In this case it is 72.
Now convert it to binary with the dec2bin() function. Then take the next function. You can find how these functions work at http://www.php.net.
OR use this piece of code:
<?php
// Call the function like this: asc2bin("text to convert");
function asc2bin($string)
{
$result = '';
$len = strlen($string);
for ($i = 0; $i < $len; $i++)
{
$result .= sprintf("%08b", ord($string{$i}));
}
return $result;
}
// If you want to test it remove the comments
//$test=asc2bin("Hello world");
//echo "Hello world ascii2bin conversion =".$test."<br/>";
//call the function like this: bin2ascii($variableWhoHoldsTheBinary)
function bin2ascii($bin)
{
$result = '';
$len = strlen($bin);
for ($i = 0; $i < $len; $i += 8)
{
$result .= chr(bindec(substr($bin, $i, 8)));
}
return $result;
}
// If you want to test it remove the comments
//$backAgain=bin2ascii($test);
//echo "Back again with bin2ascii() =".$backAgain;
?>
Comments
If you're trying to access a specific part of a string you can treat it like an array as-is.
$foo = 'bar';
echo $foo[0];
output: b
4 Comments
EvanK
For this kind of string access, I believe curly brace notation is preferable (otherwise you risk confusing the hell out of anyone else maintaining your code). For example: $foo{0}
McAden
Unless I'm mistaken, Curly brace notation for this is deprecated in PHP 6
McAden
Ah, here it is: us.php.net/language.types.string The "Note" under the heading - "String access and modification by character"
o0'.
@EvanK: for any kind of access, I believe square brace notation is preferable (otherwise you risk confusing the hell out of anyone else maintaining your code). For example avoid: $foo{0}