Replace array key with their associated value in PHP array

Sometimes, In big project we need to replace array key with their associated value at that time you can learn from this article. For example if you have all country array but that array have key like 0,1,2,3,4 and value is country both, like in below example.

<?php
$array = array("Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay");
print_r($array);
?>

Output:

Array
(
    [0] => Ukraine
    [1] => United Arab Emirates
    [2] => United Kingdom
    [3] => United States
    [4] => Uruguay
)

But you want to make array like country as key and value both and we want to have a function that will take this array as input and return an array that would look like:

Array
(
    [Ukraine] => Ukraine
    [United Arab Emirates] => United Arab Emirates
    [United Kingdom] => United Kingdom
    [United States] => United States
    [Uruguay] => Uruguay
)

Replace array key with their associated value in PHP array

We can do that using array_combine() function of PHP array.

array_combine

The array_combine() function creates an array by using the elements from one “keys” array and one “values” array. But both arrays must have equal number of elements.

Syntax

array_combine(keys,values);

<?php
$array = array("Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay");
print_r(array_combine($array, $array));
?>

Output:

Array
(
    [Ukraine] => Ukraine
    [United Arab Emirates] => United Arab Emirates
    [United Kingdom] => United Kingdom
    [United States] => United States
    [Uruguay] => Uruguay
)

You can use foreach loop also replace array key with their associated value

<?php
$array      = array("Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay");
$new_array  = array();
foreach($array as $key=> $value){
    $new_array[$value] = $value;
}
print_r($new_array);
?>

Leave A Reply

Your email address will not be published.