Solved

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

Posted on 2011-09-30
5
259 Views
Last Modified: 2012-05-12
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
Comment
Question by:cnxmax
  • 3
5 Comments
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 36893472
If this works, I would not change it.  You can't really improve on the code very much.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 36893479
But that said, this is probably what I would do...
foreach ($someArray as $key => $nothing)
{
    $newarray[$key] = 0;
}

Open in new window

0
 
LVL 17

Accepted Solution

by:
Chris Harte earned 500 total points
ID: 36893502
This is the function you are after

$levels = array_fill_keys($levelIds,  0);
0
 

Author Closing Comment

by:cnxmax
ID: 36893547
Bingo.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 36893567
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

Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question