Avoid Invalid argument supplied for foreach() Error

Avoid Invalid argument supplied for foreach() Error

Looping array we different ways such as while,foreach and for loop.
We use one of the above technique base on the situation.
Take an example we have and array of key not as 0,1,2…..
in such situation we cannot use for loop so we should use
foreach.We cannot say the input supplied is always an array
some time we may get empty value for that and we get this
error
“Invalid argument supplied for foreach()..”

To avoid this we can use the
functions

key(Mixed array); // Which returns the key of current array element
current(Mixed array); // Which returns the value of current array element
next(Mixed array); /// Which moves to pointer to next array element

Instead of using like this

foreach($array as $tmp){
echo $tmp;
}

we can use

for($i=0;$i<count($array);$i++){
key($array);
current($array);
next($array);
}

both do the same process

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.