Re: Weird Behaviour of Array
| From: | Ashley Sheridan | Date: | Sun, 04 Mar 2012 14:53:53 +0000 |
| Subject: | Re: Weird Behaviour of Array | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-316865@lists.php.net to get a copy of this message | ||
On Sun, 2012-03-04 at 20:01 +0530, Ruwan Pathmalal wrote:
> Hi People,
> I confused with weird behaviour of array. Following is my script.
>
> <?php
> $array = array(
> '12_1'=>array(
> 56=>array(
> 23=>'23',
> 33=>'33')
> ),
> '12_5'=>array(
> 55=>'55'
> )
> );
>
> $array['12_5'][55][45] = '45';
> $array['12_5'][55][56] = '76';
> $array['12_5'][55][85] = '85';
> $array['12_5'][55][96] = '96';
> print_r($array);
> ?>
>
> Output is -:
> Array ( [12_1] => Array ( [56] => Array ( [23] => 23 [33] => 33 ) ) [12_5]
> => Array ( [55] => 55 4 7 8 9 ) )
>
> Sometime this is because, first time $array['12_5'][55] not an array. I
> assigned value to it like array. (I suppose overwrite key and then assign
> given value as key value pair). See this part of output [12_5] => Array (
> [55] => 55 4 7 8 9 ). It compose 4 from 45, 7 from 76, 8 from 85 like that
> (first digit of assigned values).
>
> I manage to overcome this problem by unsettling $array['12_5'][55] before
> assigning value to it.
>
> But I want to know why this happening or is this PHP bug ? (Clear
> explanation for situation :) )
>
> Thanks
> Ruwan
I think because $array['12_5'][55] is originally a string, and PHP
allows you to treat them as arrays of characters (like C++) what is
happening is some odd setting of values within the string. This is why
when you unset the value or define it as a blank array it is working as
expected.
--
Thanks,
Ash
http://www.ashleysheridan.co.uk