Answer the question
In order to leave comments, you need to log in
How can I get the next and previous element relative to $array[$i]?
Hello. I need a function that will return the previous or next elements of an array relative to the given ones. And if the last element is given, then the next one will be the first.
In fact, I can write all the conditions, where "if the first and left, then the last", "if the last and right, then the first", "if just right, then +1" and "if just left, then -1"
But I feel like I'm trying to reinvent what php already has - I just don't know about it.
Is there a more elegant solution?
$array = [
"первый",
"второй",
'третий',
'четвёртый'
];
function get($action, $i, $array){
if (count($array) === $i + 1 && $action === 'right') {
$result = $array[0];
} else
if ($i === 0 && $action === 'left') {
$result = end($array);
} else
if ($action === 'right') {
$result = $array[$i+1];
} else
if ($action === 'right') {
$result = $array[$i-1];
}
return [$array, $action, $i, $result];
}
p( get('left', 0, $array) );
Answer the question
In order to leave comments, you need to log in
function get($action, $i, $array){
$result = '';
if ( $action == 'left' ) {
$result = ( $i == 0 ) ? $array[count($array)] : $array[$i--];
} else {
$result = ( $i == count($array) ) ? $array[0] : $array[$i++];
}
return $result;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question