28
$binary = b'Binary string';

What consequences does it have to create a string as binary?

I couldn't find any hint about that in the documentation. Just found this little curiosity while looking through the language_scanner.

NikiC
  • 100,734
  • 37
  • 191
  • 225
  • 1
    This was [added in 5.2.1](http://php.net/manual/en/language.types.type-juggling.php) - What version of PHP are you using? – Sampson Jan 20 '11 at 16:05
  • 1
    I'm using PHP 5.3.5. But why is that of importance? – NikiC Jan 20 '11 at 16:06
  • 1
    @RobertPitt: Would it? Wouldn't it at least need to be `b . 'String'` to be concatenated? Imho it would simple throw `Unexpected T_CONSTANT_ENCAPSED_STRING`. – NikiC Jan 20 '11 at 16:25
  • in PHP 5.2 it would just echo Binary String: http://codepad.org/6XGKX8ES, but it dose throw that syntax error on some versions – RobertPitt Jan 20 '11 at 16:28

3 Answers3

27

This is a forward compatibility token for the never-to-be-released PHP version 6, which should have had native unicode support.

In PHP6, strings are unicode by default, and functions operate at the unicode character level on them. This "b" means "binary string", that is, a non unicode string, on which functions operate at the byte level.

This has no effect in PHP != 6, where all strings are binary.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
2

Binary casting is available since 5.2.1 but will not take effect until 6.0 when unicode strings also take effect.

Which explains why this does nothing special right now for me on a server using 5.2.6:

<?php
$t = b"hey";
var_dump($t);
//string(3) "hey"

$s = (binary)"hey";
var_dump($s);
//string(3) "hey"
?>
mercator
  • 28,290
  • 8
  • 63
  • 72
brian_d
  • 11,190
  • 5
  • 47
  • 72
0

Convert to string

$binary = preg_replace('/[[:^print:]]/', '', $binary);
  • 3
    Hi, welcome to Stack Overflow. Thanks for taking the time and contributing an answer! Please note, however, that the question was about the 'b' in front of the string and what it means / what's the point of creating a binary string. Your post doesn't actually answer that. If you have general remarks, consider posting them as comments instead of answers once you gained sufficient reputation. Until then, focus on answering the actual questions. – Lutz Nov 27 '19 at 12:27