Learn
Ordered Arrays
Shifting and Unshifting

We saw that array_pop() and array_push() deal exclusively with the end of the array (the index at the length of the array minus 1). PHP also provides functions for adding and removing elements from the beginning of an array (index 0).

The array_shift() function removes the first element of an array and returns that value. Each of the elements in the array will be shifted down an index. For example, the element that was previously at the 3rd index will now be located at the 2nd.

$adjectives = ["bad", "good", "great", "fantastic"]; $removed = array_shift($adjectives); echo $removed; //Prints: bad echo implode(", ", $adjectives); // Prints: good, great, fantastic

Just like array_pop(), array_shift() reduces the length of the array, and the deleted element is gone for good.

The array_unshift() function takes an array as its first argument. The arguments that follow are elements to be added to the beginning of the array. It returns the new number of elements in the array.

$foods = ["pizza", "crackers", "apples", "carrots"]; $arr_len = array_unshift($foods, "pasta", "meatballs", "lettuce"); echo $arr_len; //Prints: 7 echo implode(", ", $foods); // Prints: pasta, meatballs, lettuce, pizza, crackers, apples, carrots

Let’s practice!

Instructions

1.

Let’s use arrays (and our imaginations) to go on a journey through the history of the 100-meter dash.

In 1991 Carl Lewis broke the record of 9.90 seconds. His record was topped in 1994 by Leroy Burrell. Next in 1996, Donovan Bailey took the record only to have his record usurped by Maurice Greene in 1999, then Tim Montgomery in 2002.

We’ve provided an array $record_holders. Use the array_unshift() function to add "Carl Lewis", "Leroy Burrell", "Donovan Bailey", "Maurice Greene", and "Tim Montgomery" to the $record_holders.

Add the names so that older records always have higher index locations than more recent records.

Note: It’s not required, but you might find it helpful to periodically print your array.

2.

Oops. Tim Montgomery’s record was invalidated. Use the array_shift() function to remove him from the $record_holders array.

3.

Great! Next up we have "Asafa Powell" in 2005 followed by "Justin Gatlin" in 2006. Use the array_unshift() function to add them to the $record_holders array.

4.

Justin Gatlin’s record was also invalidated. Use the array_shift() function to remove him from the $record_holders array.

5.

Ok, last but not least, use array_unshift() function to add "Usain Bolt" to the $record_holders array.

Folder Icon

Take this course for free

Already have an account?