A
A
Anastasia2021-06-17 20:02:40
PHP
Anastasia, 2021-06-17 20:02:40

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

2 answer(s)
E
Edward, 2021-06-17
@nastya97core

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;
}

P
pLavrenov, 2021-06-17
@pLavrenov

It seems to me that we need to get rid of else-if
To get "left" - check if i - 1 < 0 then return the last one, if not less then return i - 1
To get "right" - check if i + 1 > count ($arr) then return the first one in the array if not more then i + 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question