-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.

NobodyNada
  • 7,529
  • 6
  • 44
  • 51
PHPLover
  • 1
  • 51
  • 158
  • 311

1 Answers1

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

Ice76
  • 1,143
  • 8
  • 16