如何在数组中找到第一个自由键 [英] How to find the first free key in an array

查看:78
本文介绍了如何在数组中找到第一个自由键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道数组实际上是PHP中的有序树.鉴于此,数组索引(整数键)不必严格按照顺序排列,甚至根本不存在.因此,给定一个像这样的数组:

We all know that arrays are actually ordered trees in PHP. Given that, an array index (integer key) need not be in any strict order or even exist at all. So, given an array like:

array( 1 => 'A', 5 => 'B', 2 => 'C', 3 => 'D', 6 => 'E', 0 => 'F' )

如何在不重新索引数组的情况下确定第一个空键的最低整数(非负数)?在这种情况下,它将是4.

How can we determine the lowest (non negative) integer of the first empty key, without re-indexing the array? In this case it would be 4.

推荐答案

通过while循环轻松解决方案:

Easy solution by while loop:

function firstFreeKey($array)
{
  $i = 0;
  while(isset($array[$i])) $i++;
  return $i;
}

$array = array( 1 => 'A', 5 => 'B', 2 => 'C', 3 => 'D', 6 => 'E', 0 => 'F' );

echo firstFreeKey($array);

输出:

4

这篇关于如何在数组中找到第一个自由键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆