"secondVal", 120=> "thirdVal",...">

Php array compression

I need to take an array that looks something like this ...

array( 11 => "fistVal", 19 => "secondVal", 120=> "thirdVal", 200 =>"fourthVal");

and convert it to ...

array( 0 => "fistVal", 1 => "secondVal", 2=> "thirdVal", 3 =>"fourthVal");

Here is what I came up with -

function compressArray($array){
    if(count($array){
        $counter = 0;
        $compressedArray = array();
        foreach($array as $cur){
            $compressedArray[$count] = $cur;
            $count++;   
        }
        return $compressedArray;
    } else {
        return false;
    }
}

I'm just wondering if there are any built-in functions in php or neat tricks to do this.

+3
source share
3 answers

you can use array_values

An example taken directly from the link,

<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>

Outputs:

Array
(
    [0] => XL
    [1] => gold
)
+10
source

Use array_valuesto get an array of values:

$input = array( 11 => "fistVal", 19 => "secondVal", 120=> "thirdVal", 200 =>"fourthVal");
$expectedOutput = array( 0 => "fistVal", 1 => "secondVal", 2=> "thirdVal", 3 =>"fourthVal");
var_dump(array_values($input) === $expectedOutput);  // bool(true)
+3
source

array_values ​​() is probably the best choice, but as an interesting note, note that array_merge and array_splice also reindex the array.

$input = array( 11 => "fistVal", 19 => "secondVal", 120=> "thirdVal", 200 =>"fourthVal");
$reindexed = array_merge($input);
//OR
$reindexed = array_splice($input,0); //note: empties $input
//OR, if you do't want to reassign to a new variable:
array_splice($input,count($input)); //reindexes $input
+1
source

Source: https://habr.com/ru/post/1741108/


All Articles