php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #41169 foreach() on empty array causes key to be created (Works with PHP 5!)
Submitted: 2007-04-23 04:36 UTC Modified: 2007-12-08 11:54 UTC
Votes:11
Avg. Score:3.8 ± 1.2
Reproduced:6 of 8 (75.0%)
Same Version:2 (33.3%)
Same OS:2 (33.3%)
From: mobile-g at softhome dot net Assigned:
Status: Wont fix Package: Scripting Engine problem
PHP Version: 4.4.6 OS: Red Hat
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2007-04-23 04:36 UTC] mobile-g at softhome dot net
Description:
------------
running a foreach loop on an empty array causes the test key to be created.

Note this code has been pulled from a class, I have kept this structure in case that has relevance.

Reproduce code:
---------------
var $myArray = Array();

foreach($this -> mayArray['value'] as $value){

    $myArray += $value;
}

Expected result:
----------------
Ideally the loop wouldn't run, or would error when trying to locate a none existant key.

Actual result:
--------------
myArray() has an empty key called "value" added to it.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-04-23 04:38 UTC] mobile-g at softhome dot net
var $myArray = Array();

foreach($this -> mayArray['value'] as $value){
    $myVAR += $value; //changed this line
}


actually it isn't asssigning to itself...
this version is correct.
 [2007-04-23 05:03 UTC] judas dot iscariote at gmail dot com
<?php

class foo {

var $myArray = Array();

    function foo() {

        foreach($this->myArray['value'] as $value){
        }

        var_dump($this->myArray);
    }
}

$foo = new Foo();


produces the behaviuor you describe with PHP4

array(1) {
  ["value"]=>
  NULL
}


PHP5 works as expected.

My suggestion for the reporter is to upgrade to PHP5 ASAP, you shouldnt be using PHP4 nowdays anyway.
 [2007-04-23 09:20 UTC] tony2001@php.net
Assigned to the maintainer.
 
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Sat Jul 04 18:01:26 2020 UTC