Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Splitting an Array into two arrays - keys array and values array

Tags:

arrays

php

Is there an easy way to split an array into two arrays, one consisting of all the keys and the other consisting of all the values? This would be a reverse to the action of array_combine. Is there an inbuilt function for doing such a task? Let's use an example array:

$array = array('Tiger' => 'Forest', 'Hippo' => 'River', 'Bird' => 'Sky');

Is there a function that will split the above array into:

$array_keys = array('Tiger', 'Hippo', 'Bird');
$array_values = array('Forest', 'River', 'Sky');
like image 776
Bululu Avatar asked Jun 04 '11 04:06

Bululu


People also ask

How can I get array values and keys into separate arrays in PHP?

Let's use an example array: $array = array('Tiger' => 'Forest', 'Hippo' => 'River', 'Bird' => 'Sky'); Is there a function that will split the above array into: $array_keys = array('Tiger', 'Hippo', 'Bird'); $array_values = array('Forest', 'River', 'Sky');

How can I split an array into two parts in PHP?

PHP: Split an array into chunksThe array_chunk() function is used to split an array into arrays with size elements. The last chunk may contain less than size elements. Specifies the array to split. If we set preserve_keys as TRUE, array_chunk function preserves the original array keys.


3 Answers

There are two functions called array_keys and array_values:

$array_keys = array_keys($array);
$array_values = array_values($array);
like image 76
Yuri Stuken Avatar answered Oct 27 '22 04:10

Yuri Stuken


There are two functions actually:

$keys = array_keys($array);
$values = array_values($array);

You can also do the exact opposite:

$array = array_combine($keys, $values);
like image 20
netcoder Avatar answered Oct 27 '22 05:10

netcoder


use array_keys and array_values

like image 4
Samuel Herzog Avatar answered Oct 27 '22 03:10

Samuel Herzog