PHP array_unshift() Function

Definition

The array_unshift() function adds a value onto the start of the array. This is the opposite of the array_shift() function.

Syntax

PHP array_unshift() Function has the following syntax.

int array_unshift ( array &arr, mixed var [, mixed ...] )

Parameter

ParameterIs RequiredDescription
arrayRequired.Array to be added
value1Required.Value to insert
value2Optional.Value to insert
value3Optional.Value to insert

Note

You can't add key/value pairs to associative arrays using array_unshift() or its counterpart, array_pop(). However, you can work around this by using array_merge().

Note 2

With array_unshift() and array_push(), if you include an array as one of the values to add, the array is added to the original array as an element, turning the original array into a multidimensional array:


<?PHP// w w w.j a  v  a 2  s  .com
$authors = array( "Java", "PHP", "CSS", "HTML" ); 
$newAuthors = array( "Javascript", "Python" ); 
echo array_push( $authors, $newAuthors ) . "\n";
print_r( $authors ); 
?>

If you instead want to add the elements of the array individually to the original array, use array_merge().

The code above generates the following result.

Example 1

Adds a value onto the start of the array


<?PHP//from  ww w  .  j a  v a 2 s. c  om
$firstname = "java2s.com";
$names = array("A", "B", "C", "D", "E");
array_unshift($names, $firstname);
print_r($names);
?>

The code above generates the following result.

Example 2

Adds two value onto the start of the array


<?PHP/*from  w  ww  . j  av  a  2s.c om*/
$authors = array( "Java", "PHP", "CSS", "HTML" ); 
echo array_unshift( $authors, "Javascript", "Python" ) . "\n"; // Displays "6" 
print_r( $authors );       
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions