1

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;
}
4
  • 1
    No, but it should only take a few minutes to write one Commented Jun 17, 2015 at 8:52
  • 1
    Beware that any uses of this function don't turn into Schlemiel the Painter's alogirthm. Commented Jun 17, 2015 at 8:57
  • What are you really trying to do here? Paint us the bigger picture please, Schlemiel. Commented Jun 17, 2015 at 9:47
  • it sounds like generators Commented Jun 18, 2015 at 2:38

2 Answers 2

2
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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.