php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #33940 array_map() fails to pass by reference when called recursively
Submitted: 2005-08-01 05:05 UTC Modified: 2005-08-10 10:24 UTC
From: david dot tulloh at infaze dot com dot au Assigned: dmitry (profile)
Status: Closed Package: Arrays related
PHP Version: 5CVS-2005-08-02 OS: *
Private report: No CVE-ID: None
 [2005-08-01 05:05 UTC] david dot tulloh at infaze dot com dot au
Description:
------------
array_map fails to work recursively.
It does not pass by reference in the inner array_map call.

Changing the line to
$ret = array_map('ref_map', &$item);
provides the expected result but throws a Call-time pass-by-reference warning.

Reproduce code:
---------------
<?php
function ref_map(&$item) {
    if(!is_array($item)) {
        $item = 1;
        return 2;
    } else {
        $ret = array_map('ref_map', $item);
        echo 'Inner return: '; print_r($ret);
        echo 'Inner item: '; print_r($item);
        return $ret;
    }
}

$a = array(array(0), 0);
$ret = array_map('ref_map', $a);
echo 'Array: '; print_r($a);
echo 'Return: '; print_r($ret);

?>


Expected result:
----------------
Inner return: Array
(
    [0] => 2
)
Inner item: Array
(
    [0] => 1
)
Array: Array
(
    [0] => Array
        (
            [0] => 1
        )

    [1] => 1
)
Return: Array
(
    [0] => Array
        (
            [0] => 2
        )

    [1] => 2
)


Actual result:
--------------
Inner return: Array
(
    [0] => 2
)
Inner item: Array
(
    [0] => 0
)
Array: Array
(
    [0] => Array
        (
            [0] => 0
        )

    [1] => 1
)
Return: Array
(
    [0] => Array
        (
            [0] => 2
        )

    [1] => 2
)


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-08-10 10:24 UTC] dmitry@php.net
Your expectation is wrong because array_map() receives arrays arguments by value. To make array_map() work as you expected you should pass arrays by reference directly.
However there is anothe bug in this case. array_map() shouldn't modify sorce array if it isn't called by reference.

This is fixed in CVS HEAD (6.0), PHP_5_1m PHP_5_0 and PHP_4_4.

See test case for more details: ext/standard/tests/array/bug33940.phpt
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 21 08:01:29 2024 UTC