Re: Weird Behaviour of Array

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 4 Mar 2012, at 14:31, Ruwan Pathmalal wrote:

> 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 :) )

Not a bug. You set $array['12_5'][55] to a string, then you try to use it as an array. Strings can be accessed as arrays.

> $array['12_5'][55][45] = '45';

This line sets the 45th character in the string to 4 (each element of a string accessed as an array can only contain a single character, so it throws the 5 away).

> $array['12_5'][55][56] = '76';
> $array['12_5'][55][85] = '85';
> $array['12_5'][55][96] = '96';

Likewise with these. You're not seeing the additional spaces because you're viewing it as an HTML page. Run it on the command line or add <pre> before the <?php to see the actual value, which is...

"55                                           4          7                            8          9"

-Stuart

-- 
Stuart Dallas
3ft9 Ltd
http://3ft9.com/
-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php




[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux