Return to Snippet

Revision: 3889
at September 29, 2007 12:26 by micmath


Updated Code
// a sparse array has non consecutive integers for the indexes,
$array = array(7=>'foo', 19=>'bar';
$array[] = 'baz';

// note that count($array) will return 3 here, not much use
foreach($array as $i => $el) {
    if(is_int($i)) { // in case this array has mixed keys
        echo $el;
    }
}

// if you want to de-sparse the array before you walk it, do this
function array_desparse(&$array, $filler=NULL) {
	$max = -1;
	for (end($array); $key = key($array); prev($array)) {
		if (is_int($key) and $key > $max) {
			$max = $key;
		}
	}
	for ($i = 0; $i <= $max; $i++) {
		if (!array_key_exists($i, $array)) {
			$array[$i] = $filler;
		}
	}
	ksort($array);
}

Revision: 3888
at September 29, 2007 11:58 by micmath


Initial Code
// a sparse array has non consecutive numbers for the indexes, like so...
$array = array(7=>'foo', 19=>'bar', favourite_icecream=>'chocolate');
$array[] = 'baz';

// for won't work here, and plain foreach returns too much
foreach($array as $i => $el) {
    if(is_int($i)) {
        echo $el;
    }
}

Initial URL

                                

Initial Description
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.

Initial Title
Dealing with sparse arrays

Initial Tags

                                

Initial Language
PHP