Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

array_unshift()

Example

Add the element “blue” to the beginning of an array.

<?php
$a=array(“a”=>“red”,“b”=>“green”);
array_unshift($a,“blue”);
print_r($a);
?>

Definition and Usage

The array_unshift() function adds new elements to the beginning of an array.

Tip: You can insert a single value or multiple values.

Note: Numeric keys will start at 0 and increment by 1, while string keys will remain unchanged.

Syntax

array_unshift(array, value1, value2, value3, …)

Parameter Values

Parameter

Description

array

Required. Providing an array.

value1

Optional. Specifies a value to insert (required in PHP versions prior to 7.3).

value2

Optional. Specifies the value(s) to insert.

value3

Optional. Specifies the value to be inserted.

Technical Details

 

Return Value:

Returns the updated number of elements in the array.

PHP Version:

4+

PHP Changelog:

PHP 7.3: This function can now be called with just the array parameter.

More Examples

Example

Display the return value.

<?php
$a=array(“a”=>“red”,“b”=>“green”);
print_r(array_unshift($a,“blue”));
?>

Example

Using numeric indices:

<?php
$a=array(0=>“red”,1=>“green”);
array_unshift($a,“blue”);
print_r($a);
?>