php 获得foreach中的第一个元素

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 获得foreach中的第一个元素相关的知识,希望对你有一定的参考价值。

<?php

//If your array has unique array values, then determining the first and last element is trivial:

foreach($array as $element) {
    if ($element === reset($array))
        echo 'FIRST ELEMENT!';

    if ($element === end($array))
        echo 'LAST ELEMENT!';
}
//This works if last and first elements are appearing just once in an array, otherwise you get false positives. Therefore, you have to compare the keys (they are unique for sure).

foreach($array as $key => $element) {
    reset($array);
    if ($key === key($array))
        echo 'FIRST ELEMENT!';

    end($array);
    if ($key === key($array))
        echo 'LAST ELEMENT!';
}

以上是关于php 获得foreach中的第一个元素的主要内容,如果未能解决你的问题,请参考以下文章