Unexpected behavior of PHP unpack()

Viewed 1938

Tests

$x = sprintf( "foo\x00bar\x00baz" );
$y = unpack( 'afoo/abar/abaz' , $x );
print_r( $y );
$x = sprintf( "foo\x00bar\x00baz" );
$y = unpack( 'a*foo/a*bar/a*baz' , $x );
print_r( $y );

Results

Array
(
    [foo] => f
    [bar] => o
    [baz] => o
)
Array
(
    [foo] => foobarbaz
    [bar] => 
    [baz] => 
)

Note that the NULL byte is always there, you can check it with hexdump.

Expected result

Array
(
    [foo] => foo
    [bar] => bar
    [baz] => baz
)

Notes

I know I can use explode to achieve a similar result. I'm not asking an alternative, I just want to understand the logic behind the a format character ("NUL-padded string" as the doc says).

Where does the "NULL" value get involved in all this?

1 Answers
Related