How to set value as key in PHP array?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post i would like to share with you how to set value as key in php array. Sometimes, we are working on php or any other framework projects and sometimes we need to change an array value as array key at that time now from this post you can learn how it work.Now In this example we will do that without using foreach loop. For example if we have all country name in array but that array have a key like 1,2,3,4… etc and the value is country name. So at that time we need to make array as like country name as key and value both. On that way we can store it on database table directly.

So here We can do that this by using array_combine() of PHP array. array_combine() take two arguments and both should be an array.

So, let’s start and see an example.

Example:

$myArray = ['1'=>'A','2'=>'B','3'=>'C','4'=>'D'];
$result = array_combine($myArray,$myArray);
print_r($result);

Read Also : How to convert Object into Array in PHP?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →