Hướng dẫn
Quảng cáo

Hàm array_unshift() trong PHP

Hướng dẫn cách sử dụng hàm array_unshift() về mảng trong lập trình PHP

Tác dụng của hàm array_unshift()

The array_unshift() function inserts one or more elements at the beginning of an array.

All numerical array keys will be modified to start counting from zero. String keys will remain the same.

The following table summarizes the technical details of this function.

Return Value: Returns the new number of elements in the array.
Changelog: Since PHP 7.3.0 this function can now be called with only one parameter (i.e. array). Previously, at least two parameters have been required.
Version: PHP 4+


The basic syntax of the array_unshift() function is given with:

array_unshift(array, value1, value2, ...);

The following example shows the array_unshift() function in action.

// Sample array
$colors = array("red", "green", "blue");

// Prepending two values to the colors array
array_unshift($colors, "yellow", "orange");


The array_unshift() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to work on.
value1, value2, ... Optional. Specifies the values to prepend to the beginning of the array.

More Examples

Here're some more examples showing how array_unshift() function actually works:

You can also prepend values to the associative arrays as demonstrated below:

// Sample array
$alphabets = array("a"=>"apple", "b"=>"ball", "c"=>"cat", "d"=>"dog");

// Prepending a single value to the alphabets array
array_unshift($alphabets, "elephant");

Bài viết này đã giúp ích cho bạn?

Bài viết mới