php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #44559 Array keys being added when returning by reference
Submitted: 2008-03-28 14:05 UTC Modified: 2008-04-01 16:56 UTC
From: kurt at surfmerchants dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.2.5 OS: Linux
Private report: No CVE-ID: None
 [2008-03-28 14:05 UTC] kurt at surfmerchants dot com
Description:
------------
When returning an array element from a function by reference, if the element key does not exist, the element key is added.

Reproduce code:
---------------
class simple
{
	var $items = array();
	
	function &getItem($name)
	{
		return $this->items[$name];
	}
}

$obj = new simple();

print "Keys before getting item:\n".print_r(array_keys($obj->items), TRUE)."\n";

$retrieved =& $obj->getItem('SHOULD_NOT_EXIST');

print "Retrieved: \n";
var_dump($retrieved);

print "Keys after getting item:\n".print_r(array_keys($obj->items), TRUE)."\n";

Expected result:
----------------
Keys before getting item:
Array
(
)

Retrieved: 
NULL
Keys after getting item:
Array
(
)


Actual result:
--------------
Keys before getting item:
Array
(
)

Retrieved: 
NULL
Keys after getting item:
Array
(
    [0] => SHOULD_NOT_EXIST
)


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-03-29 19:48 UTC] felipe@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

Says the documentation:
"Note: If you assign, pass or return an undefined variable by reference, it will get created."

http://docs.php.net/manual/en/language.references.whatdo.php
 [2008-04-01 16:45 UTC] kurt at surfmerchants dot com
Yeah, I see that now in the docs, thanks. 
However, just because it's in the docs doesn't make it "right" -- this behavior is *very* confusing when it happens. I wonder if any other language does this; it basically means that you can't count on the contents of any array being correct when you iterate over it, unless you created that array yourself are the only one that has accessed it.
 [2008-04-01 16:56 UTC] felipe@php.net
Use isset() for such occasion.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 25 17:01:29 2024 UTC