Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress a php array

Tags:

arrays

php

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

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

and convert it to...

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

This 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 curious if there is any built-in functionality in php or neat tricks to do this.

like image 584
Derek Adair Avatar asked Dec 07 '22 03:12

Derek Adair


2 Answers

You can use array_values

Example taken directly from the link,

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

Outputs:

Array
(
    [0] => XL
    [1] => gold
)
like image 159
Anthony Forloney Avatar answered Dec 09 '22 18:12

Anthony Forloney


Use array_values to get an array of the 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)
like image 41
Gumbo Avatar answered Dec 09 '22 18:12

Gumbo