简体   繁体   中英

Find next highest value in an array

I have an string converted to an array with 1 to 7 values eg 3, 1234567, 1234, 357, 46 etc

Given any number between 1 and 7, how do I find the next value in the array?

$str=12345;
$arr=str_split($str);

$end=end($arr);

if ($day==$end) {
    $next=reset($arr);
} else {
    $loc=array_search($day, $arr)+1;
    $next=$arr[$loc];
}

print $next;

If day is 1 the above returns 2 and if day is 5 above returns 1 both of which are correct but if day is 6 or 7 then it does not return the correct value which should be 1 - likewise if the array is 1245 and day is 3 it again does not return the correct value which should be 4.

What do I need to do to make the above return the correct values in all scenarios?

$values = array_filter($arr, function($v) use($day) {
    return $v > $day;
});

$value = $values ? array_shift($values) : array_shift($arr);

Probably not optimal and untested but it should work.

Of course there will be many different ways to perform this task. I'll demonstrate one efficent approach that uses decrementation in a loop to find the next number i the sequence without generating an array. Before looping, declare a fallback value of the first number in the haystack string.

Here are 5 different test cases where the number after 5 is sought.

Code: ( Demo )

$tests = [
    '3',
    '1234567',
    '1234',
    '357',
    '46'
];

$find = 5;
++$find;
foreach ($tests as $test) {
    $found = $test[0];
    for ($i = strlen($test) - 1; $i >= 0; --$i) {
        if ($test[$i] < $find) {
            break;
        }
        $found = $test[$i];
    }
    echo "Found $found\n";
}

Output:

Found 3
Found 6
Found 1
Found 7
Found 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM