|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #70771 foreach($array['non_existant_key'] as &$row) silently modifies array
Submitted: 2015-10-22 17:29 UTC Modified: 2015-10-22 18:12 UTC
From: stuckinabox at live dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: Irrelevant OS: all
Private report: No CVE-ID: None
 [2015-10-22 17:29 UTC] stuckinabox at live dot com
Seems logical that an error should be thrown since that index doesnt exist in the array. instead, the index is silently added with a value of null. All versions of php >5.4 and all versions of HHVM are affected.


Test script:

$data = [

foreach($data['non_existant_key'] as &$row)



Expected result:
undefined index

Actual result:
array is silently modified to include the non existant key


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2015-10-22 18:12 UTC]
-Status: Open +Status: Not a bug
 [2015-10-22 18:12 UTC]
A simpler case that illustrates the same issue:

    $ref =& $data['non_existant_key'];

This will not throw a notice by design. You are allowed to take a reference to a key that does not exist yet -- it will be initialized to NULL.

When you iterate by reference you are also implicitly creating a reference to the iterated entity.
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Thu Jan 21 19:01:27 2021 UTC