Solved

PHP: Add key and value to beginning of array

Posted on 2011-09-20
5
340 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
  • 3
5 Comments
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
Try:

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

Open in new window

0
 
LVL 13

Expert Comment

by:haloexpertsexchange
Comment Utility
0
 
LVL 16

Author Comment

by:hankknight
Comment Utility
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 21

Expert Comment

by:Kim Walker
Comment Utility
Correction:

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

Open in new window

0
 
LVL 21

Accepted Solution

by:
Kim Walker earned 500 total points
Comment Utility
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

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 …
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

763 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

13 Experts available now in Live!

Get 1:1 Help Now