tags:

views:

67

answers:

1

I know it'd be trivial to code myself, but in the interest of not having more code to maintain if it's built in to PHP already, is there a built-in function for "compressing" a PHP array? In other words, let's say I create an array thus:

$array = array();
$array[2000] = 5;
$array[3000] = 7;
$array[3500] = 9;

What I want is an array where $array[0] == 5, $array[1] == 7, $array[2] == 9.

I could do this:

function array_defragment($array) {
    $squashed_array = array();
    foreach ($array as $item) {
        $squashed_array[] = $item;
    }
    return $squashed_array;
}

...but it seems like the kind of thing that would be built in to PHP - I just can't find it in the docs.

+12  A: 

Just use array_values:

$array = array();
$array[2000] = 5;
$array[3000] = 7;
$array[3500] = 9;

$array = array_values($array);
var_dump($array === array(5, 7, 9));
Gumbo
Perfect, thanks!
Charles