php.net |  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
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: stuckinabox at live dot com
New email:
PHP Version: OS:

 

 [2015-10-22 17:29 UTC] stuckinabox at live dot com
Description:
------------
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.

Repro: https://3v4l.org/UNIe4

Test script:
---------------
<?php

$data = [
    'existant_key'=>[]
];

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

print_r($data);

?>
https://3v4l.org/UNIe4

Expected result:
----------------
undefined index

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

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-10-22 18:12 UTC] nikic@php.net
-Status: Open +Status: Not a bug
 [2015-10-22 18:12 UTC] nikic@php.net
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-2025 The PHP Group
All rights reserved.
Last updated: Sat Jul 12 05:01:33 2025 UTC