mixed array_shift ( array array)
int array_unshift ( array array, mixed var [, mixed ...])
int array_push ( array array, mixed var [, mix ...])
mixed array_pop ( array array)
If you have ever used the C++ Standard Template Library, you will know how useful the deque (double-ended queue, pronounced "deck") type is. If you have never used STL, or C++ for that matter, a deque allows you to store elements in an array-like structure, then work with either the very first element or the very last element. This might not sound useful, after all we've already seen that PHP lets you read from any variable in an array at any time, so why would it be good to work with only the first and last elements?
Well, using what you know already, how would you insert a variable at the very first position in your array? Or how would you read the first element and remove it from the array? It would be tricky, for sure - and that's where the deque principle comes in.
Array_shift() takes an array as its only parameter, and returns the value from the front of the array while also removing it from the array. Consider this script:
<?php $names = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Danny", "Joe"); $firstname = array_shift($names); var_dump($names); ?>
If you run that script, you will see that $firstname is set to "Johnny", and the array $names now only has the values Timmy, Bobby, Sam, Tammy, Danny, and Joe - Johnny gets removed. To remove an element from the end of an array (as opposed to the start), there is also array_pop(), which works in the same way as array_shift(). Both these functions also have opposites, array_unshift() and array_push(), which place an element into an array at the start or at the end respectively. This next script should clear up any confusion:
<?php $names = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Danny", "Joe"); $firstname = array_shift($names); // First element of $names is now Timmy; last is Joe array_push($names, $firstname); // first is Timmy; last is now Johnny $firstname = array_pop($names); // first is Timmy; last is Joe again array_unshift($names, $firstname); // first is Johnny, last is Joe var_dump($names); ?>
Extracting the first and last variable from an array is a very popular task, so try to keep these functions in the back of your mind.
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Swapping keys and values >>
Previous chapter: Checking whether an element exists
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.