tags:

views:

350

answers:

3

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 that would look like:

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

I wonder if it is possible to use array_walk_recursive or something similar...

+1  A: 

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))

Edit: Noah came up with the same array_combine() version a bit faster.

Artem Russakovskii
thank you for your help also
jimiyash
A: 

This should do it.

function toAssoc($array) {
 $new_array = array();
 foreach($array as $value) {
  $new_array[$value] = $value;
 }  
 return $new_array;
}
Alan Storm
+8  A: 

You can use the array_combine function, like so:

$numbers = array('first', 'second', 'third');
$result = array_combine($numbers, $numbers);
Noah Medling
ah, that looks more like it.
jimiyash