Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

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

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
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.

840 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