Brad
Brad

Reputation: 12252

array function to create new array with values as being the keys?

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

Answers (2)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

You can do with array_fill_keys this way:

$final = array_fill_keys($ids, "Green");

Upvotes: 3

Jon
Jon

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

Related Questions