0

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!

1
  • May be array_fill might work? Commented Jun 3, 2013 at 19:30

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 Okay, that was fast! :)
Thanks for the tip on the decimals.
3

You can do with array_fill_keys this way:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.