1

Can someone please tell me if this method of doing foreach has drawbacks?

class someclass {
  function foo() {
    foreach ($my_array as $this->key => $this->value) {
      $this->bar();
      $this->baz();
    }
  }
  function bar(){
    //do something with $this->key or $this->value
  }
  function baz(){
    //do something with $this->key or $this->value
  }
}
2
  • 6
    Ew. That is all. Commented Sep 29, 2011 at 2:56
  • the biggest draw back is readability as u can already see ^^ Commented Sep 29, 2011 at 3:11

2 Answers 2

2

It's pretty inefficient as you are essentially setting the key to an associative array on each loop. I would keep them local and then assign them when the loop is done if you need to store them. Also, pass the values to the methods when you call them.

class SomeClass {
    function foo($myArray) {
       foreach ($myArray as $key => $value){
           $this->bar($key);
           $this->baz($value);
        }
        $this->key = $key;
        $this->value = $value;
     }
    function bar($key){
     //do something with $this->key or $this->value
    }
    function baz($value){
     //do something with $this->key or $this->value
    }
 }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Matt. I have always done the way you suggested. Just thought of this a few minutes ago and was curious.
It's pretty inefficient as you are essentially setting the key to an associative array on each loop. Huh? How do you mean? $this->key is set to a scalar value (namely the key of the array item) on each iteration. Or am I misinterpreting what you are saying?
I am referring to the time it takes to resolve the property name to a memory address. This is because the class implementation is something like a hash table or associative array.
0

If you need the keys and values to be accessible publicly in your methods, I'd go with:

class someclass{
    function foo($my_array){
       foreach ($my_array as $key => $value){
           $this->loopArray[$key] = $value;
           $this->bar();
           $this->baz();
        }

     }
    function bar(){
        //do something with $this->key or $this->value

    }
    function baz(){
        //do something with $this->key or $this->value
    }

 }

 $obj = new someclass();
 $my_array = array('value1','value2');
 $obj->foo($my_array);
 var_dump($obj->loopArray);

Outputs:

array(2) { [0]=> string(6) "value1" [1]=> string(6) "value2" }

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.