How to Set Value as Key in PHP Array?

By Hardik Savani November 5, 2023 Category : PHP

Hello Dev,

In this quick example, let's see php set value as key array. I explained simply step by step php change array value by key. If you have a question about php array value as key then I will give a simple example with a solution. We will look at an example of php make array value as key.

Sometimes, when working on large PHP or other framework projects, we may need to convert array values to array keys. In such cases, we can learn from this post. In this example, we can achieve this without using a foreach loop. For instance, if we have an array of countries with numerical keys and country names as values, we may need to convert it to an array with country names as both keys and values, so that we can store it directly in a database table.

We can accomplish this using the array_combine() function of PHP, which takes two arguments, both of which should be arrays. Let's take a look at an example.

Example:

<?php

$myArray = ['1'=>'US','2'=>'India','3'=>'Brazil','4'=>'Germany'];

$result = array_combine($myArray,$myArray);

print_r($result);

Output:

Array

(

[US] => US

[India] => India

[Brazil] => Brazil

[Germany] => Germany

)

I hope it can help you...

Tags :
Shares