Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

PHP: Add key and value to beginning of array

Posted on 2011-09-20
5
Medium Priority
?
421 Views
Last Modified: 2012-05-12
Using PHP, how can I add a key and value to the beginning of an array?
<pre><?php

$zzz=array();

$zzz['b']='Banana';
$zzz['c']='Cherry';
$zzz['d']='Durian';

$zzz = array_merge($zzz,'a'->'Apple');

print_r($zzz);

?>
</pre>

Open in new window

0
Comment
Question by:hankknight
[X]
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
  • 3
5 Comments
 
LVL 22

Expert Comment

by:Kim Walker
ID: 36568486
Try:

$zzz = array_merge($zzz,array('a'->'Apple'));

Open in new window

0
 
LVL 13

Expert Comment

by:haloexpertsexchange
ID: 36568497
0
 
LVL 16

Author Comment

by:hankknight
ID: 36568553
xmediaman, your idea gives a parse error.

halo, your idea does not preserve the key.

Please provide a working example based on the code I posted, thanks!
0
 
LVL 22

Expert Comment

by:Kim Walker
ID: 36569003
Correction:

$zzz = array_merge($zzz,array('a'=>'Apple') );

Open in new window

0
 
LVL 22

Accepted Solution

by:
Kim Walker earned 2000 total points
ID: 36569015
If you want "a" to be first in the array order, simply reverse the order of the array_merge arguments:

$zzz = array_merge(array('a'=>'Apple'),$zzz);

Open in new window

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
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 look for a specific file type in a local or remote server directory using PHP.

730 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