Find the next key of an array

Asked

Viewed 21 times

1

I have an array that serves as a list of steps

$Lista = ['a','b','c','d'];

I need to find the next value after entering the current value. Example: I’m in step B I want the code to tell me the next step is C.

Details: My list does not have an ordered order, at any time I can remove or add a step.

1 answer

1


The list will always be sorted, if you have:

$Lista = ['a','b','c','d'];

IS exactly same as having:

$Lista = [0 => 'a', 1 => 'b', 2 => 'c', 3 =>'d'];

That is, even if removing the c, the d will take the index of 2. If nothing has order, then there is no magic that will make you guess which order you want to follow.


So, assuming you have a code like:

$Lista = ['a','b','c','d'];
$PontoAtual = 'c';

If you want to use these two values to get d and b could use the array_flip, as:

echo $Lista[array_flip($Lista)[$PontoAtual] + 1];

That would be trouble if $PontoAtual was invalid (example: if it was x, that does not exist) or was the last value (for example, if it were d, which is last). Then you could do something like:

$Lista = ['a','b','c','d'];
$PontoAtual = 'c';

$IndiceDoPontoAtual = (array_flip($Lista)[$PontoAtual] ?? false); if ($IndiceDoPontoAtual === false){
    echo "Ponto atual inválido";
    return;
}

$ProximoPonto = $IndiceDoPontoAtual + 1; if(count($Lista) <= $ProximoPonto) {
    echo "O proximo ponto não existe, uma vez que está no último ponto";
    return;
}

printf("O próximo ponto é %s", $Lista[$ProximoPonto]);

Test.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.