Wednesday, July 13, 2011

a question regarding PHP string & array

$data['first'] = 'Hello world';
$data['first']['second'] = 'Good morning';
//what is the result of following output?
echo $data['first'];

The result is 'Gello world'. Why is that?

First, when php has to use any non-numeric character/string as a number, php will treat it as 0. Try this:

//print 0
echo (int)'second';
//print 2
echo (int)'2';

So, $data['first']['second'] is actually $data['first'][0]. 

Second, when we treat a string as an array(just like char array in C), and try to access its elements through array index like $data['first'][0], $data['first'][0] only refers to one single character, which is 'H' initially. Even we try to assign 'Good morning' to $data['first'][0], PHP will only take the first character, which is 'G'. So $data['first'] becomes 'Gello world' 

No comments: