从阵列中找到第一个可用的ID

编程入门 行业动态 更新时间:2024-10-13 00:36:22
本文介绍了从阵列中找到第一个可用的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

本文发布于:2023-11-22 06:15:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616284.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第一个   阵列   中找到   ID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!