NYCPHP Meetup

NYPHP.org

[nycphp-talk] Array handling - Why does this happen?

DeWitt, Michael mjdewitt at alexcommgrp.com
Thu Feb 12 16:04:14 EST 2004


Dan,

Thank you very much for figuring this one out.  

It is clear to me now that one cannot extend the elements (structure?) of an
array by merely adding on a new element syntactically where elements already
have values. 

I think I was not really following what was going on because of PHP's array
handling flexibility like in this example:

$a=array();
$a['1']['2']['3']='the';
$a['2']['2']['3']['4']=' answer';

echo $a['1']['2']['3'];
echo $a['2']['2']['3']['4'];

Outputs:

the answer

Call me crazy, but I tend to build associative arrays on the fly and haven't
run into this issue until now, so this was of real interest to me. 

Mike

> -----Original Message-----
> From:	Dan Cech [SMTP:dcech at phpwerx.net]
> Sent:	Thursday, February 12, 2004 12:59 PM
> To:	NYPHP Talk
> Subject:	Re: [nycphp-talk] Array handling - Why does this happen?
> 
> It's not immediately clear what's going on in the code you presented, 
> but I have extracted the relevant code, which is:
> 
> $answer = array (
>    'Yes' => array (
>      'Yes' => 'Yes',
>      'count' => 0
>    ),
>    'No' => array (
>      'No' => 'No',
>      'count' => 0
>    )
> );
> 
> $val='Yes';
> $val1='No';
> 
> $answer[$val]['count']=8888;
> echo $answer[$val]['count']."<br>";
> 
> $answer[$val1]['count']=9999;
> echo $answer[$val1]['count']."<br>";
> 
> $answer = array (
>    'Yes' => 'Yes',
>    'No' => 'No'
> );
> 
> $val='Yes';
> $val1='No';
> 
> $answer[$val]['count']=8888;
> echo $answer[$val]['count']."<br>";
> 
> $answer[$val1]['count']=9999;
> echo $answer[$val1]['count']."<br>";
> 
> As you can see, in the first case $answer[$val] is an array, whereas in 
> the second case $answer[$val] is a string.
> 
> What's happening I think is that you are unwittingly invoking the 
> (deprecated) syntax for accessing a string by character:
> 
> $mystring = 'hello';
> 
> echo $mystring{0};
> echo $mystring[0];
> 
> both should result in 'h';
> 
> This syntax can also be used to assign into a string...which is what is 
> happening here.
> 
> The 'count' is being to converted to the integer 0, and the first 
> character in the string is being overwritten with the first character 
> from the value you are assigning.
> 
> So in the second example:
> 
> $answer[$val] is 'Yes'
> 
> Then we do:
> 
> $answer[$val]['count'] = 8888;
> 
> which is equivalent to:
> 
> $answer[$val]{0} = 8888;
> 
> so $answer[$val] is now '8es'
> 
> then we do:
> 
> echo $answer[$val]['count'];
> 
> which is equivalent to:
> 
> echo $answer[$val]{0};
> 
> which results in '8'
> 
> An interesting little problem for sure.
> 
> Dan
> 



More information about the talk mailing list