Create a member array with equal keys and values ​​from a regular array

I have an array that looks like

$numbers = array('first', 'second', 'third'); 

I want to have a function that will take this array as input and return an array that will look like this:

 array( 'first' => 'first', 'second' => 'second', 'third' => 'third' ) 

I wonder if array_walk_recursive or something like that can be used ...

+60
arrays php
Jul 01 '09 at 1:09
source share
3 answers

You can use the array_combine function, for example:

 $numbers = array('first', 'second', 'third'); $result = array_combine($numbers, $numbers); 
+128
Jul 01 '09 at 1:19
source share

This simple approach should work:

 $new_array = array(); foreach($numbers as $n){ $new_array[$n] = $n; } 

You can also do something like:

array_combine(array_values($numbers), array_values($numbers))

+4
Jul 01 '09 at 1:12
source share

That should do it.

 function toAssoc($array) { $new_array = array(); foreach($array as $value) { $new_array[$value] = $value; } return $new_array; } 
0
Jul 01 '09 at 1:14
source share



All Articles