从阵列中找到第一个可用的ID [英] Finding first available ID from an array

查看:92
本文介绍了从阵列中找到第一个可用的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个数组是这样的:

Given an array like this:

Array => (
  [0] => 1,
  [1] => 2,
  [2] => 3,
  [3] => 5,
  [4] => 6
)

什么是找到阵列和ndash的第一'可用'标识的最简单的方法;也就是说,在序列中的第一个值 [1,2,3 ... n]的不阵列中是否存在?在这种情况下,正确的答案应该是 4

What is the easiest way to find the first 'available' ID in that array – that is, the first value in the sequence [1,2,3...n] that does not exist in the array? In this case, the correct answer would be 4.

我可以使用一些做while循环或用各种变量温度,但是这是一个有点乱,所以我很感兴趣,看看是否有人能想出一个聪明的解决方案。

I can do this using some while loops or sorts with temp variables but that's a bit messy, so I'm interested to see if anyone can come up with a 'clever' solution.

推荐答案

我的PHP技能是有点生疏,但不能使用的 范围 和的 和array_diff

My PHP skills are a bit rusty, but couldn't you use range and array_diff:

$missing = array_diff(range(1, end($myArray)+ 1), $myArray);
echo $missing[0];

与大肚Ulmanen的修正更新(我告诉过你我的PHP是生锈; - ))

Updated with Tatu Ulmanen's corrections (i told ya my PHP was rusty ;-))

这篇关于从阵列中找到第一个可用的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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