A while ago I started trying to do a tip of the day series. I kept getting distracted and sort of ran out of material. I'm going to retry this with a new twist - rather than deal with abstracts I'm going to pick a function and go over it. PHP has several hundred functions so I shouldn't have a shortage of material.

Today's function is array_unshift

array_unshift lets you prepend to an array. Consider

PHP Code:
$myArray = array (
  
'Berries',
  
'Cucumbers',
  
'Lettuce'
); 
If we wanted to add to the end of the list, this is easy enough.

PHP Code:
$myArray[] = 'Potatoes'// equivalent to array_push($myArray, 'Potatoes'); 
But what if we want to add to the front of the list? That's what array_unshift is for.

PHP Code:
array_unshift($myArray'Apples'); 
Keep in mind the following about array_unshift: All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

Literal keys mean string keys such as $myArray['mykey'];

Related Functions
  • array_shift removes the first element of the array and returns its value. So it undoes what array_unshift does.
  • array_push appends to the end of the array. It rarely sees use in PHP because of the language shorthand shown above.
  • array_pop removes the last element of the array (undoing array_push).