Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

PHP: Add key and value to beginning of array

Posted on 2011-09-20
5
Medium Priority
?
435 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 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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

This article discusses how to create an extensible mechanism for linked drop downs.
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
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 …
Suggested Courses

926 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