Edit report at https://bugs.php.net/bug.php?id=19140&edit=1
ID: 19140 Comment by: mail at waclawjacek dot com Reported by: jc at mega-bucks dot co dot jp Summary: foreach fails on empty or unitialized variable Status: Not a bug Type: Bug Package: Arrays related Operating System: Red Hat Linux 7.2 PHP Version: 4.2.2 Block user comment: N Private report: N New Comment: I found this idea somewhere on the net, thanks, it's pretty neat, still, it was a surprise to find out this is how foreach() behaves after years of using while() to loop through an array of database results. Previous Comments: ------------------------------------------------------------------------ [2012-09-01 15:51:49] ras...@php.net Often that points to a bug. If you are ok with it, just cast it. No need for an is_array() check. eg. foreach( (array)$a as $val ) ... ------------------------------------------------------------------------ [2012-09-01 15:45:59] mail at waclawjacek dot com I second jc. It would be nice not to have to do if ( is_array() ) before every foreach(), like you don't have to with while(), when the variable is null. ------------------------------------------------------------------------ [2002-08-28 05:41:03] der...@php.net FYI: I clearified this in the manual, it will show up in a few days online. Derick ------------------------------------------------------------------------ [2002-08-28 05:32:48] jc at mega-bucks dot co dot jp Neglectful coding? Why do you consider it neglectful coding if I do this for an array but good coding for a string? PHP treats null strings as empty strings, why doesn't it do the same for arrays? All I want to know is, what is the documented behaviour for foreach on a null array. If there is no documented behaviour, let's add to the documentation. Something like: "foreach will fail on an unitialized (null) array". I had assumed that since PHP is usually treats null strings as empty strings it would do the same with null arrays. I was wrong. I tried to find documentation on what foreach will do in the case of a null array and could not find any. I agree with you that this is neglectfull coding. It would be nice if there was documentation to back it up :) ------------------------------------------------------------------------ [2002-08-28 05:17:20] cy...@php.net if you insist on neglectful coding, lower your error_reporting level. ------------------------------------------------------------------------ The remainder of the comments for this report are too long. To view the rest of the comments, please view the bug report online at https://bugs.php.net/bug.php?id=19140 -- Edit this bug report at https://bugs.php.net/bug.php?id=19140&edit=1