NIF
NIF

Reputation: 472

PHP Array : a function that return next object in array (with array and current object param)?

My question is : is there a function that return next object in array (with array and current object param) ? Can you help me to code the best way ?

function get_next($array, $currentObject) {

    .... ?
    return $nextObject;
}

Upvotes: 1

Views: 115

Answers (2)

user4580220
user4580220

Reputation:

Here is my code, this

for($i = 0; $i < count($array) && $array[i] != $currentObject; $i++);

I would not put this into function at all, I would put it were I am calling that function but here is your function:

function get_next($array, $currentObject) {
    for($i = 0; $i < count($array) && $array[i] != $currentObject; $i++);
    return array[$i];
}

Simple linear and works in any occasion.

Upvotes: 1

NIF
NIF

Reputation: 472

function get_next($array, $currentObject) {
    $key = array_search($currentObject, $array);
    if($key!==false) {
       $key++; // Work only on numbers and letter
       if(isset($array[$key])) {
          return $array[$key];
       } else {
          return null;
       }
    } else {
       return null;
    }
}

Upvotes: 2

Related Questions