php - 在 PHP 中检测数组的 "actual"结尾

标签 php arrays null comparison iteration

假设我有一个数组如下:

$array = array('a', 'b', 0, 'c', null, 'd');

现在,我当然可以使用 foreach 轻松地遍历它:

foreach($array as $value){
    var_dump($value);
}

一切都很好。但是,如果我想做一个“peek”以查看我是否在最后一个元素上,则以下将不起作用:

reset($array);
while($value = current($array)){
    var_dump($value);
    if(next($array)){
        // this won't be accurate because of the 0 element
    }
}

好的,所以我做一个更严格的测试:

if(null !== next($array)){
    // this STILL won't be accurate because of the null element
}

是使用带索引的 for 循环和算术窥视的唯一解决方案吗?我不认为这对于维护关联键的完整性而不需要大量的游手好闲是可行的。 (我知道我的例子没有举例说明这个警告,但我会将 current() 换成 each(),和 next( )current())

是否没有万无一失的方法来准确判断数组指针是否已经移过数组末尾,而不管数组元素值是什么(null, 0)

警告;虽然当然有很多使用临时变量的解决方案,但对于此操作来说需要这样的东西似乎既肮脏又愚蠢。我很惊讶不存在简明的解决方案。


好吧,这绝不是一个完美的解决方案,因为 array_keys() 正在创建一个新数组注意 但这里是:

$array = array('alpha', 'b' => 'beta', null, 'g' => 'gamma', false, 0, 'delta', null);
list($end) = array_keys(array_slice($array, -1, 1, true));
foreach($array as $key => &$value){
    // do important stuff on each element
    if($key !== $end){
        // do important stuff on all but last element
    }
}

注意我换掉了 array_slice()array_keys() 所以没有创建完整的 key 副本。最初是:array_slice(array_keys($array), -1);,看来修改后的内存会更好。


为那些在这里绊倒的人做的另一个编辑;这些可能在类似情况下有用:

// each returns the current element, but assigns to the referenced arguments
// the "peeked" values. they're missing checks, but it's a start.

function peek(Array &$array, &$value){
    $value = next($array);
    return prev($array);
}

function peek_key(Array &$array, &$key){
    next($array);
    $key = key($array);
    return prev($array);
}

function peek_each(Array &$array, &$key, &$value){
    next($array);
    list($key, $value) = array(key($array), current($array));
    return prev($array);
}

最佳答案

http://www.php.net/next
Note: You won't be able to distinguish the end of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.

while (list($key, $val) = each($fruit)) {
    echo "$key => $val\n";
}

each 返回一个数组或 false。这是非常独特的。

关于php - 在 PHP 中检测数组的 "actual"结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6936561/

相关文章:

php - 将文件名添加到数据库而不上传

java - 如何停止在数组中打印 null

arrays - Excel VBA - 分配数组更改 LBound 和 UBound

java - char* (Array) 强制转换为 unsigned long + 1?

Lua 尝试调用 nil

sql - 比较空值时的奇怪行为 SQL

php - MySQL几种排序条件: WHERE and LIMIT in the same query

php - 警告 : "pecl/mongo" is deprecated in favor of "channel:///mongodb"

java - 如何从php读取字符串到android studio(java)

java - 如何声明数组元素为空?