php 数组 删除第一个元素,如何从PHP中的数组中删除第一个元素?

要从数组中删除第一个元素或值, 请使用array_shift()函数。此函数还返回数组的移除元素, 如果数组为空, 则返回NULL。删除第一个元素后, 其他元素的键将被修改, 并且仅当键为数字时, 数组才从头开始编号。

它是PHP的内置数组函数, 可将元素从数组的开头移出。

返回值

用于从数组中删除第一个元素的array_shift()函数返回删除的元素。如果数组为空, 它也会返回NULL。

例如:使用字符串元素

$color = array("Blue", "Red", "Black", "Green", "Gray", "White");

echo "Arraylist: ";

print_r($color);

$remove = array_shift($color);

echo "Removed element from array is: ";

print_r($remove);

echo " Updated arraylist: ";

print_r($color);

?>

输出

从给定数组的第一个位置删除元素” Blue”, 并在给定输出中显示更新的列表。

Arraylist: Array ( [0] => Blue [1] => Red [2] => Black [3] => Green [4] => Gray [5] => White )

Removed element from array is: Blue

Updated arraylist: Array ( [0] => Red [1] => Black [2] => Green [3] => Gray [4] => White )

示例:使用数字键

$game = array(1 => "Carom", 2 => "Chess", 3 => "Ludo");

echo "Removed element: ".array_shift($game). "";

print_r($game);

?>

输出

Removed element: Carom

Array ( [0] => Chess [1] => Ludo )

示例:使用数值

$numbers = array(25, 12, 65, 37, 95, 38, 12);

$removed = array_shift($numbers);

echo "Removed array element is: ". $removed;

echo " Update array is: ";

print_r($numbers);

?>

输出

从给定数组的第一个位置删除元素25, 并在下面显示更新的列表。

Removed array element is: 25

Update array is: Array (

[0] => 12

[1] => 65

2] => 37

[3] => 95

[4] => 38

[5] => 12

)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值