Take the tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Please help! I have been staring at this for too long. I have a property of an object that is an array of objects. I want to pass in an object to a method of the parent object and search through that array property for a match, and if one is found return the index. Otherwise, I need it to return -1. For some reason, it is not iterating. If I echo out what should be the $order->product property (where the index is pointing during the loop), it is unchanging. I have dumped the array and I know it contains different values. I can show you a big var dump, but I figured I would first ask if there is a simple error or something else that is obvious to you that I have missed.

public function getItemIndex($prod) {
    if (isset($this->orders)){
      foreach($this->orders as $key => $order) {
        if ($order->product == $prod) { //if I echo this $order->product to the screen, it is unchanging
          return $key;
        } else { return -1; }
      }
    }
    else {
      return -1;
    } 
  }

If anyone has any ideas, I am open to discuss and post more information as needed. Thank you for your time.

share|improve this question
1  
Can you show $this->orders (or part of it)? –  popnoodles yesterday
1  
in_array just returns a boolean. I'll add the var_dump, one sec... –  eightArmCode yesterday
1  
as in if (!in_array((array)$this->orders, $prod)) return -1; EDIT, Oh you want the key. –  popnoodles yesterday
add comment

1 Answer

up vote 5 down vote accepted

You are ALWAYS returning a value on the first iteration, either the $key or -1. Try removing the else statement that you currently have. This will allow you to fully iterate over the entire array.

public function getItemIndex($prod) {
    if (isset($this->orders)){
        foreach($this->orders as $key => $order) {
            if ($order->product == $prod) { //if I echo this $order->product to the screen, it is unchanging
                return $key;
            }
        }
    }

    return -1;
}

This will ONLY return -1 once it has iterated over everything and found nothing to match. It will still return $key if it finds a match.

share|improve this answer
 
Shouldn’t it be return -1;? You seemed to have missed the semicolon. –  Sharanya Dutta yesterday
 
Indeed, it has been fixed. –  Justin Wood yesterday
 
thank you so much! –  eightArmCode yesterday
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.