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

cnxmaxAsked:
Who is Participating?
 
Chris HarteConnect With a Mentor ThaumaturgeCommented:
This is the function you are after

$levels = array_fill_keys($levelIds,  0);
0
 
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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.