• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 298
  • Last Modified:

Create an Array with all Zero Values from another Array's Keys

I'm curious if there's an easier way to do what I'm doing bellow, perhaps with array_map or array_walk or something like that?
$levelIds = array_keys($someArray);
$levels = array();
foreach ($levelIds as $levelId) {
	$levels[$levelId] = 0;
}

Open in new window

0
cnxmax
Asked:
cnxmax
  • 3
1 Solution
 
Ray PaseurCommented:
If this works, I would not change it.  You can't really improve on the code very much.
0
 
Ray PaseurCommented:
But that said, this is probably what I would do...
foreach ($someArray as $key => $nothing)
{
    $newarray[$key] = 0;
}

Open in new window

0
 
Chris HarteThaumaturgeCommented:
This is the function you are after

$levels = array_fill_keys($levelIds,  0);
0
 
cnxmaxAuthor Commented:
Bingo.
0
 
Ray PaseurCommented:
Ha!  I have never used that function.  Maybe because it's so logical and easy to use the iterator.  Looks like it does not get a lot of play -- the most recent user-contributed note is over three years old!
http://php.net/manual/en/function.array-fill-keys.php
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now