Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I flatten an associative array into an array with only values in PHP?

I have an array that has keys and values. For eg:

Array (
    [name] => aalaap
    [age] => 29
    [location] => mumbai
)

I want to convert the keys from this into values, but I want the values to apear right after the keys. For eg:

Array (
    [0] => name
    [1] => aalaap
    [2] => age
    [3] => 29
    [4] => location
    [5] => mumbai
)

I can easily write an iteration function that will do this... for eg:

array_flatten($arr) {
    foreach ($arr as $arrkey => $arrval) {
        $arr_new[] = $arrkey;
        $arr_new[] = $arrval;
    }
    return $arr_new;
} 

...but I'm trying to find out if there's any way this can be accomplished using array_combine, array_keys, array_values and/or array_merge, preferably in one, so i don't need to use a custom function.

Is there?

like image 549
aalaap Avatar asked Dec 03 '22 15:12

aalaap


2 Answers

Your own solution is probably the cleanest solution, so converting it to a "one-liner":

$array = array('name' => 'aalaap','age' => 29, 'location' => 'mumbai');
$answer = array();

array_walk($array, create_function('$val,$key', 'global $answer; $answer[]=$key; $answer[]=$val;'));

var_dump($answer);

This avoids unnecessary and expensive array copies or sorting.

Alternatively, lose the global:

array_walk($array, create_function('$val,$key,$result', '$result[]=$key; $result[]=$val;'), &$answer);
like image 183
Just Jules Avatar answered Dec 28 '22 23:12

Just Jules


I don't think this is possible - with the built-in functions you'll end up with all the keys then all the values:

$a = array('a' => 'A', 'b' => 'B', 'c' => 'C');

$a = array_merge(array_keys($a), array_values($a));
print_r($a);

You're going to have to use a loop like this:

$b = array();
foreach ($a as $key => $value)
{
    $b[] = $key;
    $b[] = $value;
}
like image 28
Greg Avatar answered Dec 28 '22 22:12

Greg