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

Hàm array_shift() trong PHP

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

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

The array_shift() function shifts or removes the first element from an array.

The following table summarizes the technical details of this function.

Return Value: Returns the value of the removed element, or NULL if array is empty or is not an array.
Version: PHP 4+

Syntax

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

array_shift(array);

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

<?php
// Sample array
$fruits = array("apple", "banana", "orange", "mango");

// Remove and get the first value from array
echo array_shift($fruits); // Prints: apple
print_r($fruits);
?>

Note: If the array keys are numeric, as in the above example, they will be reset to start from 0. However, arrays using associative or string keys will not be affected.


Parameters

The array_shift() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to work on.

More Examples

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

The following example shows how to remove the first element from an associative array.

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

// Remove and get the first value from array
echo array_shift($alphabets); // Prints: apple
print_r($alphabets);
?>

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

Bài viết mới

Advertisements