对于一个php数组,该如何删除该数组的第一个元素或者最后一个元素呢?其实这两个过程都可以通过php自带的函数 array_pop 和 array_shift 来完成,下面就具体介绍一下如何来操作。
(1)使用 array_pop 删除数组的最后一个元素,例如:
<p>$user=array('apple','banana','orange');</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/2249">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175679998691134.png" alt="超级简历WonderCV">
</a>
<div class="aritcle_card_info">
<a href="/ai/2249">超级简历WonderCV</a>
<p>免费求职简历模版下载制作,应届生职场人必备简历制作神器</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="超级简历WonderCV">
<span>271</span>
</div>
</div>
<a href="/ai/2249" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="超级简历WonderCV">
</a>
</div>
$result=array_pop($user);<br />print_r($result);<br /><p>print_r($user);</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/7fc7563c4182" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">PHP免费学习笔记(深入)</a>”;</p>结果将是:
orange
array('apple','banana')
(2)使用 array_shift 删除数组的第一个元素,例如:
<p>$user=array('apple','banana','orange');</p>$result=array_shift($user);<br />print_r($result);<br /><p>print_r($user);</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/7fc7563c4182" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">PHP免费学习笔记(深入)</a>”;</p>结果将是:
apple
array('banana','orange')
其实删除数组的第一个元素还可以使用 array_splice 这个函数,即:
$user=array_splice($user,1); //删除数组第一个元素,注意此时返回的是被删除后的新的数组
array_pop() 弹出并返回 array 数组的最后一个单元,并将数组 array 的长度减一。如果 array 为空(或者不是数组)将返回 NULL。
array_shift() 将 array 的第一个单元移出并作为结果返回,将 array 的长度减一并将所有其它单元向前移动一位。所有的数字键名将改为从零开始计数,文字键名将不变。如果 array 为空(或者不是数组),则返回 NULL。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号