Make an array have same keys as values.

Have you ever wanted to make an array with same keys as the values? for example, we want an array of fruits.

$my_array = array('apple','orange','mango');

By default, when you don’t specify a key for each array element a default numeric key is assigned, the above be assigned key indexes as:

Array
(
   [0] => apple
   [1] => orange
   [2] => mango
)

But that’s not actually what you want right? thanks to the built in PHP array function array_combine() we can combine the array values with the keys. Let’s try the following

$my_array = array('apple','orange','mango');
$my_array = array_combine($my_array,$my_array);

Now, let’s run a print_r($my_array) to see how it looks, the results will be:

Array
(
   [apple] => apple
   [orange] => orange
   [mango] => mango
)

There we go! you can use this idea if you have a country list array with short country name for the array key, this happened to me when I had a country list array where the key for country Canada was CA. I just used array_combine() and everything worked like a charm!

Leave a Reply