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
 [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

Add a Patch

Pull Requests

Add a Pull Request

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-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 04:01:29 2024 UTC