-3

I'm using PHP 7.2.11 on my machine that runs on Windows 10 Home Single Language 64-bit Operating System.

I tried below codes :

Code Snippet No. 1

<?php
$str = 'abc\0def';
echo strlen($str); // Outputs 8
?>

Code Snippet No. 2

<?php
$str = "abc\0def";
echo strlen($str); // Outputs 7
?>

I'm not understanding why the same function is producing two different outputs for the same string? One time it gives output 8 and another time 7

Why so?

Whether the function strlen() is binary-safe and multibyte-safe or not? The PHP manual hasn't mentioned these details on the respective function's page.

5
  • There is absolutely no point in abusing PHP and its developers. Just ask a question
    – RiggsFolly
    Commented Nov 16, 2018 at 19:25
  • Note the difference of single and double quotes! And escape characters
    – RiggsFolly
    Commented Nov 16, 2018 at 19:27
  • The backslash in the double quoted var is actually an escape character, and isn’t part of the string?
    – Sbrn
    Commented Nov 16, 2018 at 19:29
  • 1
    Feeling a little silly now are we?
    – RiggsFolly
    Commented Nov 16, 2018 at 19:30
  • I think there is more to this than just a double quotes string being escaped. strlen on "\0" still returns one, and prints nothing.
    – Ice76
    Commented Nov 16, 2018 at 19:39

1 Answer 1

5

The double quotes escape \0 while the single quote does not.

The escape character \ works in a string with double quotes. Escaping a digit has special functionality. However, escaping the zero, 0, tells the processor to read the two following octal characters and process them. Since the next two characters in your string are not octal digits, the processor stop reading them, and returns the equivalent of \000, which is still counter as a character but is nothing when output, hence you seeing nothing in place of it when it is printed but still counted towards the length.

Examples:

strlen( "abc\0def" ); // outputs 7, prints: abcdef

strlen( "abc\000def" ); // outputs 7, prints: abcdef

strlen( "abc\061def" ); // outputs 7, prints: abc1def

More can be read about escape sequences following 0, or other digits/characters here

1
  • 2
    Likewise, you'd probably have this same exact problem in other languages if you escaped a character in a string. Commented Nov 16, 2018 at 19:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.