Bug->Doc #72234 [Nab]: Calling foreach on non-array is ignored
| From: | requinix@php.net | Date: | Tue, 17 May 2016 22:39:50 +0000 |
| Subject: | Bug->Doc #72234 [Nab]: Calling foreach on non-array is ignored | ||
| References: | 1 | Groups: | php.doc.bugs |
| Request: | Send a blank email to doc-bugs+get-13452@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=72234&edit=1
ID: 72234
Updated by: requinix@php.net
Reported by: nickdnk at hotmail dot com
Summary: Calling foreach on non-array is ignored
Status: Not a bug
-Type: Bug
+Type: Documentation Problem
-Package: *General Issues
+Package: Scripting Engine problem
Operating System: Windows
PHP Version: 7.0.6
Block user comment: N
Private report: N
New Comment:
If you have ideas on how to make the documentation more clearly indicate that foreach does, in fact,
work on objects then feel free to hit the Edit link in the top-right corner of the page and submit
whatever changes you think are necessary.
Previous Comments:
------------------------------------------------------------------------
[2016-05-17 22:29:54] nickdnk at hotmail dot com
But, the link clearly states (for the first form, which is what I used as example): "It [The
first form] loops over the *array* given by *array_expression*. On each iteration, the value of the
current element is assigned to $value..."
- when not iterating an array, why are we not seeing at least a warning? Would there ever be a
situation where you'd legitimately use foreach on a non-array object? If so please enlighten
me. Not a single one of the examples in the documentation for foreach use a non-array object.
------------------------------------------------------------------------
[2016-05-17 20:33:12] requinix@php.net
foreach on an object is allowed. You aren't seeing anything because the $obj is empty.
http://php.net/manual/en/control-structures.foreach.php
https://3v4l.org/CCrFo
------------------------------------------------------------------------
[2016-05-17 20:13:06] nickdnk at hotmail dot com
Description:
------------
Hello
If passing a variable (let's say a stdClass) to the foreach method, it does not produce an
error. It silently does not loop the object (since it cannot).
I'm no expert, but I'd say that at least a warning should be raised if trying to iterate a
non-array object. I'm sorry if this is intentional, but I do believe an error was raised in
5.6.
Test script:
---------------
$obj = new stdClass();
foreach ($obj as $anObj) {
error_log("nothing is output here, obviously, but no error either");
}
Expected result:
----------------
I expect an error or warning to occur, since I'm traversing a non-array.
Actual result:
--------------
Nothing happens at all.
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=72234&edit=1