Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array copy values to keys in PHP [duplicate]

Tags:

arrays

php

I have this array:

$a = array('b', 'c', 'd'); 

Is there a simple method to convert the array to the following?

$a = array('b' => 'b', 'c' => 'c', 'd' => 'd'); 
like image 710
kusanagi Avatar asked May 30 '11 11:05

kusanagi


People also ask

Can a PHP array have duplicate keys?

Arrays contains unique key. Hence if u are having multiple value for a single key, use a nested / multi-dimensional array. =) thats the best you got.

How do I copy values from one array to another in PHP?

The getArrayCopy() function of the ArrayObject class in PHP is used to create a copy of this ArrayObject. This function returns the copy of the array present in this ArrayObject.

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

How do I copy an array element to another array in PHP?

$arr1 = array_merge ( $arr1 , $arr2 ); echo "arr1 Contents:" ; // Use for each loop to print all the array elements. Using array_push Method: This method pushes the second array element in the first array in-place.


1 Answers

$final_array = array_combine($a, $a); 

Reference: http://php.net/array-combine

P.S. Be careful with source array containing duplicated keys like the following:

$a = ['one','two','one']; 

Note the duplicated one element.

like image 124
KingCrunch Avatar answered Oct 16 '22 00:10

KingCrunch