How to Set Value as Key in PHP Array?
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Convert String into Array in PHP?
- How to Remove Multiple Keys from PHP Array?
- PHP - How to Reindex Array Key After Unset Key?
- How to Get Specific Key Value from Multidimensional Array PHP?
- How to Remove Key from Array in Laravel?
- How to Convert Array Values to Lowercase in PHP?
- How to Convert Object into Array in PHP?
- How to Remove Specific Element by Value from Array in PHP?
- How to Get Maximum Key Value of Array in PHP?
- How to Remove Empty Values from Array in PHP?
- How to Add Prefix in Each Key of PHP Array?
- How to Get Minimum Key Value of Array in PHP?
- How to Remove Null Values from Array in PHP?
- How can Make an Array from the Values of Another Array's Key Value?