2010
12-25

What empty foreach do in PHP

While ago I was fighting with one bug. There was code witch was working, but stop working when I add empty foreach.
  1. //that work with rest of code
  2. function fun(){
  3. $table= array();
  4. //...
  5. return $table;
  6. }
  7.  
  8. //that do not work with rest of code
  9. function fun(){
  10. $table= array();
  11. //...
  12. foreach( $table as $key => $val ){}
  13. return $table;
  14. }
  15.  
It tuck my some time before I find out what does it change. There was a lot of code so it wosn't easy.
Here is code that help me to realize what foreach change:
  1.  
  2. //...
  3. $table= fun();
  4. $first= current($table);
  5. //...
  6.  
fun() was usualy returing table with only one element, never empty. So wibout foreach it was working. But when I run even empty foreach the current element in $table have been changed to one after last, so current($table) was returning FALSE. Here is correct way of doing such thinks:
  1.  
  2. //...
  3. $table= fun();
  4. $first= reset($table);
  5. //...
  6.  
But as there was lot of code I decide to repair it in different way.
  1. //...
  2.  
  3. function fun(){
  4. $table= array();
  5. //...
  6. foreach( $table as $key => $val ){
  7. //...
  8. }
  9. reset($table);
  10. return $table;
  11. }
  12.  
  13. //...
Now current(fun()) will give me first element.

2 Coments.

  1. Xesenix says:

    Speeking of php bug try this one http://bugs.php.net/bug.php?id=29992
    when you use two foreach loops one after another and first uses references like &$item and second uses $item you can`t guess what will happen to array you are looping trough. Best of all is that php authors don`t agree its a bug.

  2. admin says:

    Yes. That’s funny bug.
    When I want to change element in array in foreach I do it like that:
    foreach( $array as $key => $item ){
    //…
    $array[$key]= $new_value;
    //..
    }

Leave a Reply

  ( Ctrl+Enter )