PHP array_unshift() Function
In this chapter you will learn:
- Definition for PHP array_unshift() Function
- Syntax for PHP array_unshift() Function
- Parameter for PHP array_unshift() Function
- Note for PHP array_unshift() Function
- Note 2 for PHP array_unshift() Function
- Example - adds a value onto the start of the array
- Example - Adds two value onto the start of the array
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
Parameter | Is Required | Description |
---|---|---|
array | Required. | Array to be added |
value1 | Required. | Value to insert |
value2 | Optional. | Value to insert |
value3 | Optional. | 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/*from j a va 2 s.c o m*/
$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/* j a v a 2 s .co m*/
$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//j a va 2 s. co m
$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.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP array_values() Function
- Syntax for PHP array_values() Function
- Parameter for PHP array_values() Function
- Example - returns an array of all the values