My inc.functions.php – Part 4 : Unshifting elements on an array and preserving keys

PHP Willow TreeThe fourth part of this series of handy little PHP functions only contains a little tip when one needs to add an element to the beginning of an array (viz. prepend, unshift) but has to preserve the (numerical) keys.

Prerequisites

Imagine you have an array of zipcodes as keys and names of cities as values:

$zipcodes = array(
	'9800' => 'Deinze',
	'8460' => 'Ettelgem',
	'9000' => 'Gent',
	'8400' => 'Oostende'
);

Now, if I were to place those into a dropdown, I’d run that array to a function like so:

function createDropdown($ddName, $arValues) {
	$toReturn = "<select name=\"$ddName\" id=\"$ddName\">\n";

	foreach ($arValues as $key => $value) {
		$toReturn .= "\t<option value=\"$key\">$value</option>\n";
	}

	$toReturn .= "</select>";

	return $toReturn;
}

Running the array above through that function would result in the following HTML:

<!-- output of echo createDropdown("test", $zipcodes); -->
<select name="test" id="test">
	<option value="9800">Deinze</option>
	<option value="8460">Ettelgem</option>
	<option value="9000">Gent</option>
	<option value="8400">Oostende</option>
</select>

Quite obvious, not?

The problem

Now, I don’t want to have “Deinze” show up in the dropdown as the first item, but I want to show “Please choose your city” as the first item (with a value of 0). A quick peek at the PHP docs tell me that I need to use array_unshift to “prepend one or more elements to the beginning of an array

array_unshift($zipcodes, "Please Choose a City");

Running the code above would float my boat, right? Wrong! The note at the phpdocs that “All numerical array keys will be modified to start counting from zero while literal keys won’t be touched”. After having run array_unshift on $zipcodes it indeed looks like this:

Array
(
    [0] => Please Choose a City
    [1] => Deinze
    [2] => Ettelgem
    [3] => Gent
    [4] => Oostende
)

The solution

The solution is to create a second array with only one item (index: “0”, value: “Please choose a city” and then merge them together, but not using the array_merge function as the function looses numerical keys too!

So what does one need to use then? Well, it might sound noobcake-ish to you but this one I didn’t know: one can actually join 2 arrays in PHP by using the mathematical + operator! Now this is something I did not expect (it looks so not-PHP-alike, not?)!

$zipcodes = array("0" => "Please Choose a City") + $zipcodes;

And yes, the array now looks like:

Array
(
    [0] => Please Choose a City
    [9800] => Deinze
    [8460] => Ettelgem
    [9000] => Gent
    [8400] => Oostende
)

And the HTML output after running the array through the createDropdown function looks like:

<select name="test" id="test">
	<option value="0">Please Choose a City</option>
	<option value="9800">Deinze</option>
	<option value="8460">Ettelgem</option>
	<option value="9000">Gent</option>
	<option value="8400">Oostende</option>
</select>

Wrapping up

To finalize, one could wrap this little trick into a function and presto, but since it would take more code to join 2 arrays through a custom built function (which only uses a + operator) it’s way more easy to “just” remember this little trick 😉

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.