Dealing with sparse arrays


/ Published in: PHP
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. // a sparse array has non consecutive integers for the indexes,
  2. $array = array(7=>'foo', 19=>'bar';
  3. $array[] = 'baz';
  4.  
  5. // note that count($array) will return 3 here, not much use
  6. foreach($array as $i => $el) {
  7. if(is_int($i)) { // in case this array has mixed keys
  8. echo $el;
  9. }
  10. }
  11.  
  12. // if you want to de-sparse the array before you walk it, do this
  13. function array_desparse(&$array, $filler=NULL) {
  14. $max = -1;
  15. for (end($array); $key = key($array); prev($array)) {
  16. if (is_int($key) and $key > $max) {
  17. $max = $key;
  18. }
  19. }
  20. for ($i = 0; $i <= $max; $i++) {
  21. if (!array_key_exists($i, $array)) {
  22. $array[$i] = $filler;
  23. }
  24. }
  25. ksort($array);
  26. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.