php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #70639 Error use link in foreach
Submitted: 2015-10-05 09:41 UTC Modified: 2015-10-09 10:43 UTC
From: alex-dev at yandex dot ru Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.4.45 OS: Windows XP, Free BSD
Private report: No CVE-ID: None
 [2015-10-05 09:41 UTC] alex-dev at yandex dot ru
Description:
------------
Array $test soured after use link in foreach.

Test script:
---------------
$test = array(1 => 1, 2 => 2, 3 => 3);
foreach($test as $key => &$value)
{
}

uasort($test, function($a, $b) {
  if($a > $b)
    return -1;
  else if($a > $b)
    return 1;
  else
    return 0;
});

print_r($test);
foreach($test as $key => $value)
{
}
print_r($test);

Expected result:
----------------
Array
(
    [3] => 3
    [2] => 2
    [1] => 1
)
Array
(
    [3] => 1
    [2] => 2
    [1] => 1
)


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-10-05 09:52 UTC] inefedor at gmail dot com
Hi

There's a problem in your comparison callback, you have the same condition in first and second 'if'.
And yes, after first foreach you have a $value is a reference to the last element of the array. So when you do the second foreach (without unsetting $value), it rewrites value of array's first element.
 [2015-10-05 16:07 UTC] stas@php.net
-Package: PHP Language Specification +Package: Scripting Engine problem
 [2015-10-05 16:08 UTC] stas@php.net
-Status: Open +Status: Not a bug
 [2015-10-05 16:08 UTC] stas@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


 [2015-10-09 10:43 UTC] alex-dev at yandex dot ru
Thank you.
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Wed Oct 07 07:00:01 2026 UTC