php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #45170 Reference and key() problem
Submitted: 2008-06-04 11:54 UTC Modified: 2008-07-06 11:56 UTC
Votes:2
Avg. Score:5.0 ± 0.0
Reproduced:2 of 2 (100.0%)
Same Version:1 (50.0%)
Same OS:1 (50.0%)
From: johnny at eiole dot com Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 5.2.6 OS: Windows
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: johnny at eiole dot com
New email:
PHP Version: OS:

 

 [2008-06-04 11:54 UTC] johnny at eiole dot com
Description:
------------
When an static array if retourned from a method, for iterating, and acceded with the key() function, the reference pointer is moved to the end of the array.

After the loop, the array is unaccessible.

Important : if you add the following line : 

$tab = testbug::getTab();

before the loop, the error does not occur.

you can use key(), current(), prev(), there is still a bug.

First tested on windows 5.2.5 version, and still present on 5.2.6 version.

There is no bug on 5.2.3 version.

Thanks for answer.



Reproduce code:
---------------
<?php
class testbug
{
	static $tab = array(
		'k1' => "elm1",
		'k2' => "elm2",
		'k3' => "elm3",
		'k4' => "elm4",
	);
	
	static function getTab()
	{
		return self::$tab;
	}
}

var_dump(testbug::getTab());
foreach (testbug::getTab() as $k => $v)
{
	key(testbug::getTab());
}
var_dump(testbug::getTab());

Expected result:
----------------
array
  'k1' => string 'elm1' (length=4)
  'k2' => string 'elm2' (length=4)
  'k3' => string 'elm3' (length=4)
  'k4' => string 'elm4' (length=4)

array
  'k1' => string 'elm1' (length=4)
  'k2' => string 'elm2' (length=4)
  'k3' => string 'elm3' (length=4)
  'k4' => string 'elm4' (length=4)


Actual result:
--------------
array
  'k1' => string 'elm1' (length=4)
  'k2' => string 'elm2' (length=4)
  'k3' => string 'elm3' (length=4)
  'k4' => string 'elm4' (length=4)

null


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-06-06 18:52 UTC] crrodriguez at suse dot de
key(testbug::getTab()) inside foreach produces undefined behaviuor, do not mix foreach with next(), key(), current() etc.. it is known to produce "strange but correct" results.
 [2008-07-06 11:56 UTC] jani@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


 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Tue Jul 22 12:00:02 2025 UTC