PHP中字节/二进制数组的字符串

How do I convert a string to a binary array in PHP?

I think you are asking for the equivalent to the Perl pack/unpack functions. If that is the case, I suggest you look at the PHP pack/unpack functions:

There is no such thing as a binary array in PHP. All functions requiring byte streams operate on strings. What is it exactly that you want to do?

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

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;
?>