加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何测试数组指针是否在foreach循环中的第一个元素

发布时间:2020-12-13 16:37:03 所属栏目:PHP教程 来源:网络整理
导读:在一个for循环它是简单的 for ( $idx = 0 ; $idx count ( $array ) ; $idx ++ ){ if ( $idx == 0 ) { // This is the first element of the array. }} 这是如何在foreach循环中完成的? 有没有像is_first()或某事的功能? 我正在寻找像: foreach ( $array a
在一个for循环它是简单的
for ( $idx = 0 ; $idx < count ( $array ) ; $idx ++ )
{
    if ( $idx == 0 )
    {
        // This is the first element of the array.
    }
}

这是如何在foreach循环中完成的?

有没有像is_first()或某事的功能?

我正在寻找像:

foreach ( $array as $key => $value )
{
    if ( /* is the first element */ )
    {
        // do logic on first element
    }
    else
    {
        // all other logic
    }
}

我在想我可以像$is_first = true一样设置一个bool然后一旦循环迭代一次,将bool设置为false.

但php有很多pre-built函数和id,而是使用…或另一种方式…

整个布尔方式似乎几乎像…欢呼:s

干杯,

亚历克斯

你可以使用“current()”
$myArray = array('a','b','c');
if (current($myArray) == $myArray[0]) {
    // We are at the first element
}

文件:http://php.net/manual/en/function.current.php

检索第一个元素的方法:

$myArray[0]

$slice = array_slice($myArray,1); 
$elm = array_pop($slice);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读