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

PHP: Add key and value to beginning of array

Posted on 2011-09-20
5
383 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 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 500 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying 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

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…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
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 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 …

856 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