I have an array like this:
$array = array(
'mango',
'apple',
'orange',
'peach'
);
I want to turn it into a new variable like this:
$options = (
'mango' => 'mango',
'apple' => 'apple',
'orange' => 'orange',
'peach' => 'peach'
);
basically I want to make the array value become the array key, I can achieve it with a loop like this:
foreach($array as $value){
$options[$value] = $value;
}
but is there any native PHP function or one-liner function that acts the same way as the above function?
You can use array_combine()
https://www.php.net/manual/en/function.array-combine.php:
$options = array_combine($array, $array);
You should probably make sure array contains only unique values first using array_unique()
to avoid key conflicts.