php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #42384 Foreach Referencing Problem
Submitted: 2007-08-22 16:21 UTC Modified: 2007-11-21 17:28 UTC
Votes:2
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: jw at coffeecup dot com Assigned:
Status: Not a bug Package: Documentation problem
PHP Version: 5.2.3 OS: OS X
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: jw at coffeecup dot com
New email:
PHP Version: OS:

 

 [2007-08-22 16:21 UTC] jw at coffeecup dot com
Description:
------------
I get a syntax error when I cast the array_expression portion of a foreach loop to an array while using the & operator on the value portion.

Reproduce code:
---------------
$arr = array(1, 2, 3, 4);
foreach ((array)$arr as &$value) {
    $value = $value * 2;
}

print_r($arr);

Expected result:
----------------
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
)

Actual result:
--------------
Parse error: syntax error, unexpected '&', expecting T_STRING or T_VARIABLE or '$' 

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-08-22 16:38 UTC] johannes@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

The value created by (array)$arr is a temporary variable which can\'t be referenced.
 [2007-08-22 16:45 UTC] jw at coffeecup dot com
Then shouldn't I get this error: 

Fatal error: Cannot create references to elements of a temporary array expression
 [2007-08-23 10:32 UTC] jani@php.net
No, you get compile time error for invalid syntax. Reclassified.
 [2007-11-21 17:28 UTC] vrana@php.net
Already documented: "This is possible only if iterated array can be referenced (i.e. is variable)."
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Tue Jul 29 10:00:02 2025 UTC