首页 > 解决方案 > 比较两个数字,如果它遵循数组中的序列

问题描述

我不太确定该怎么做,但情况就是这样。

我有一个遵循特定顺序的字符串数组。

$array = ['A','B','C','D','E'];

我有两个带字符串的输入,我想做的是根据给定的数组检查两个输入字符串是否按顺序排列。

例如

$array = ['A','B','C','D','E'];
$input1 = 'B';
$input2 = 'D';

//this should return true

但是,如果是这种情况

 $array = ['A','B','C','D','E'];
 $input1 = 'D';
 $input2 = 'A';

 //this should return false

$input1应该总是先于$input2

我已经尝试了几种使用循环的方法来做到这一点,但我无法得到想要的结果。

感谢任何帮助。谢谢!

标签: phploopslogic

解决方案


你可以找到两个输入的索引array_search()

为了使两个输入按顺序排列,第一个输入的索引必须低于第二个输入的索引。如果没有找到也array_search()返回。false

function inSequence($array, $input1, $input2) {
    $index1 = array_search($input1, $array);
    $index2 = array_search($input2, $array);

    if($index1 === false || $index2 === false) return false;

    return $index1 < $index2;
}

推荐阅读