php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #49068 Using undefined assoc array index does not cause notice inside foreach
Submitted: 2009-07-26 22:09 UTC Modified: 2009-07-27 10:24 UTC
From: simon+php at thulbourn dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.*, 6SVN (2009-07-26) OS: *
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: simon+php at thulbourn dot com
New email:
PHP Version: OS:

 

 [2009-07-26 22:09 UTC] simon+php at thulbourn dot com
Description:
------------
An array with no associative keys doesn't throw a notice or error when 
one is used as an associative keyed array.

Reproduce code:
---------------
<?php

	$array = array('foo', 'bar', 'baz');
	
	foreach ($array as $a) {
		echo $a['foo'];
	}

?>

Expected result:
----------------
Notice: Undefined index

Actual result:
--------------
fbb

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-07-26 23:07 UTC] rasmus@php.net
That has nothing to do with a foreach.  The same effect can be seen with:

$a = 'foo';
echo $a['bar'];

$a is a string which is essentially an array of characters with numerical indices.  Given that, 'bar' is converted to an integer, so you end up with $a[0] which does exist, so no warning.
 [2009-07-27 10:04 UTC] simon+php at thulbourn dot com
I believe that it should issue a warning rather than converting to an 
integer.

It seems like a retarded action to convert the string to a 0, if I was 
to use a numeric index that doesn't exist, I'd receive a notice. Some 
consistency would be nice.)
 [2009-07-27 10:20 UTC] simon+php at thulbourn dot com
Granted, I could have provided a better sample case so:

$a = array('foo');

// echo a index that doesn't exist
echo $a['bar'];

PHP should produce a notice claiming an undefined index 'bar', instead 
it outputs the first char of the 0 index, in this case 'f', it's 
obviously converting the string to a 0 instead of producing the notice.)
 [2009-07-27 10:24 UTC] simon+php at thulbourn dot com
Sorry, the new test code was wrong, here's one that proves my point

$blah = "foo";echo $blah["frog"];)
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Mon Jul 14 14:01:31 2025 UTC