/ Published in: PHP
This snippet assumes you want to walk the numbered array items only, as you would with a normal for loop, but a for loop up to count($array) won't work with a sparse array because the highest array index will always be higher than the array count.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// a sparse array has non consecutive integers for the indexes, $array[] = 'baz'; // note that count($array) will return 3 here, not much use foreach($array as $i => $el) { echo $el; } } // if you want to de-sparse the array before you walk it, do this function array_desparse(&$array, $filler=NULL) { $max = -1; $max = $key; } } for ($i = 0; $i <= $max; $i++) { $array[$i] = $filler; } } }