Binary cast is available in PHP?

Posted on

Question :

PHP has a cast (which until then I did not know), called binary .

Example of Manual :

$binary = (binary)$string;
$binary = b"binary string";

According to the PHP Manual:


(binary) – convert to binary string

I saw that a user still posted the following:


Cast a string to binary using PHP < 5.2.1


(convert a string to binary in versions prior to PHP 5.2.1)


$binary = unpack('c*', $string);

With the test I performed in PHP 5.6, the result was as follows:

$string = "My String";

$binary = (binary)$string;
$binary = b"binary string";

var_dump($binary); // string(13) "binary string"

That is, returns the same value of the string (even with the cast for binary ).

The question is: is this functionality really available (being bug from my PHP) or will it just be a future implementation (as they say, “In PHP 6”)?


Answer :

Following the @gmsantos instructions, I created this Bug Reporting in PHP.

According to the response of the user identified as, the reason why binary does not work as expected is as follows:


(binary) is a forward compatibility token for the now abandoned “PHP 6”. It
  behaves the same way as doing (String) Cast in “PHP 5”.

If someone can help me translate, thank you. But I’ll give you an interpretation (not a translation):


This is a keyword that was added in advance to the (now abandoned)
  PHP 6. The cast for binary behaves in the same way as cast for string in PHP 5.


First the manual says it will be available in PHP 6. Or another version since even here PHP is a mess. So you can not test now.

This type of operation should not be a cast . But it’s PHP, we should already be accustomed.

You are changing the value obtained with cast . I can not imagine why. This is why the result was shown. If you take the new assignment after the cast , in thesis it would give the expected result if you still fix another error.

There are no real examples of how this will work so it’s complicated to figure out what the shape is, I’m going to kick in here what might be:

$string = "10011101";
$binary = (binary)$string;
$binary = b"10011101";

In both cases the number will be an integer value of 157. I imagine.

In PHP 5.2.1 you can do otherwise, not this one.

I’ve already told you about the quality of the manual, especially the Portuguese version. It may be that this is not even present in the next version of PHP. It may be until this was discussed but they never decided to put it in the language. Do not rely on speculation.

An attempt to make it work was no ideone . If this is not this, you need to find a source that teaches you to do it right.


Leave a Reply

Your email address will not be published. Required fields are marked *