what enpty 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.
Here is code that help me to realize what foreach change:
//that work with rest of code
function fun(){
$table= array();
//...
return $table;
}
//that do not work with rest of code
function fun(){
$table= array();
//...
foreach( $table as $key => $val ){}
return $table;
}
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:
//...
$table= fun();
$first= current($table);
//...
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:
//...
$table= fun();
$first= reset($table);
//...
But as there was lot of code I decide to repair it in different way.
//...
function fun(){
$table= array();
//...
foreach( $table as $key => $val ){
//...
}
reset($table);
return $table;
}
//...
Now current(fun()) will give me first element.