Solved

PHP: Add key and value to beginning of array

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

Technology Partners: 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

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
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…
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.
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 …

615 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