Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the built-in PHP function for "compressing" or "defragmenting" an array?

Tags:

arrays

php

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.

like image 914
Charles Avatar asked Feb 26 '26 19:02

Charles


1 Answers

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));
like image 181
Gumbo Avatar answered Mar 01 '26 07:03

Gumbo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!