Create an assoc array with equal keys and values from a regular array

PhpArrays

Php Problem Overview


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

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

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

Php Solutions


Solution 1 - Php

You can use the array_combine function, like so:

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

Solution 2 - Php

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

Solution 3 - Php

This should do it.

function toAssoc($array) {
	$new_array = array();
	foreach($array as $value) {
		$new_array[$value] = $value;
	}		
	return $new_array;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjimiyashView Question on Stackoverflow
Solution 1 - PhpNoah MedlingView Answer on Stackoverflow
Solution 2 - PhpArtem RussakovskiiView Answer on Stackoverflow
Solution 3 - PhpAlan StormView Answer on Stackoverflow