Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set array key same as value [duplicate]

Tags:

php

I have a question that seems obvious but I can't reproduce it yet. Well, let's say I have an array:

$array = ('apple', 'orange', 'banana');

So I would actually like to have the same array but with the same keys as the values, something like this:

array(
    'apple' => 'apple',
    'orange' => 'orange',
    'banana' => 'banana'
);

How would you do that?

like image 756
Diand Avatar asked May 19 '26 08:05

Diand


1 Answers

You can use array_combine and combine the array with itself. But beware that Illegal values for key will be converted to string. This means you also might lose duplicates after the string conversion. Example:

$array = array('apple', 'orange', 'banana',[], 'Array');
$array = array_combine($array,$array);
var_dump($array);

3v4l link without duplicates, 3v4l link with duplicate after string conversion

like image 84
jh1711 Avatar answered May 20 '26 22:05

jh1711