Reputation: 12252
I have an array:
$ids = array(1 => '3010', 2 => '10485', 3 => '5291');
I want to create a new array that takes the values of the $ids array and sets them as the keys of a new array, having the same value.
The final array would be:
$final = array('3010' => 'Green', '10485' => 'Green', '5291' => 'Green');
This will be used in apc_add().
I know I can accomplish this by looping thru it.
$final = array();
foreach($ids as $key => $value):
$final[$value] = 'Green';
endforeach;
But I was wondering if there was php function that does this without having to use a forloop, thanks!
Upvotes: 0
Views: 49
Reputation: 167162
You can do with array_fill_keys
this way:
$final = array_fill_keys($ids, "Green");
Upvotes: 3
Reputation: 437336
You are looking for array_fill_keys
.
$final = array_fill_keys($ids, "Green");
However, be aware that strings that are decimal representations of integers are actually converted to integers when used as array keys. This means that in your example the numbers that end up as keys in $final
will have been transformed to integers. Most likely won't make a difference in practice, but you should know about it.
Upvotes: 5