note 43444 deleted from ref.array by aidan

From: Date: Sun, 09 Oct 2005 09:14:53 +0000
Subject: note 43444 deleted from ref.array by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-96738@lists.php.net to get a copy of this message
Note Submitter: brooklynphil hotmail com ---- was browsing, and saw some array flattening functions... then i remembered i wrote one a while ago, and i wanted to compare code. to my surprise, the code was basically the same, except my code preserves keys: <?php function array_flatten(&$a,$pref='') { $ret=array(); foreach ($a as $i => $j) if (is_array($j)) $ret=array_merge($ret,array_flatten($j,$pref.$i)); else $ret[$pref.$i] = $j; return $ret; } ?> the flattened array will have its numerical keys converted to strings, however, due to a glitch* in php, these string keys might be converted back to integers! <?php $qqq= array(array(array(12)),array(56),array(14,1)); pretty($qqq); pretty(array_flatten($qqq));?> will render: <?php /*array(3){[0]=>array(1){[0]=>array(1){[0]=>int(12)}} [1]=>array(1){[0]=>int(56) } [2]=>array(2){[0]=>int(14) [1]=>int(1)} } array(4) { ["000"]=> int(12) [0]=> int(56) [1]=> int(14) [2]=> int(1)}*/?> as you can see the firsrt array 'tree' is flattened successfully, because "000" does not convert to 0, but the subsequent 'tree's are converted from e.g. "10" to 0... (why 0? i would have thought 10) seeding the prefix with something that forces a string conversion, alleviates this problem (and shows that its not my code, per se): <?php var_dump(array_flatten($qqq,"~")); /*array(4) { ["~000"]=> int(12) ["~10"]=> int(56) ["~20"]=> int(14) ["~21"]=> int(1)}*/?> --Phil * not really sure if this is a glitch. here is what the manual says: <?php /* A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). There are no different indexed and associative array types in PHP; there is only one array type, which can both contain integer and string indices. */ ?> in http://www.php.net/manual/en/language.types.array.php is there any way to circumvent this behaviour and force string keys? ive tried casting to no avail...

« previous php.notes (#96738) next »