Solved

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

Posted on 2011-09-30
5
241 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 108

Expert Comment

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

Expert Comment

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

Open in new window

0
 
LVL 16

Accepted Solution

by:
Chris Harte earned 500 total points
Comment Utility
This is the function you are after

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

Author Closing Comment

by:cnxmax
Comment Utility
Bingo.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

728 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now