php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #36997 array_map() fails when array is passed to callback function by reference
Submitted: 2006-04-06 15:21 UTC Modified: 2006-04-06 17:02 UTC
From: o dot veujoz at free dot fr Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.1.2 OS: Windows
Private report: No CVE-ID: None
 [2006-04-06 15:21 UTC] o dot veujoz at free dot fr
Description:
------------
Problem with array_map() function :

With php 5.0.4, when we pass an array to callback function by reference, the function modifies its arguments.

It is not the case with php 5.1.2. 

I read the bug number 33940 where "Dmitry" wrote : 

"To make array_map() work as you expected you should pass
arrays by reference directly."

So there is apparently a solution. I did try a lot of changes in my script but no one works as expected. 

For example, the code below works fine in PHP 5.1.2 but an error is generated in PHP 5.0.4 :

array_map('callback', &$arr);

The only way to make the script works on both PHP versions has been consisting in not using the parameters passed by reference (it does not correspond to the original problem).

$arr = array_map('callback', $arr);

Is it really a bug or is my code bad ?

Note: the allow_call_time_pass_reference has been turned off in both PHP versions.

Reproduce code:
---------------
function callback(&$val) {
    $val['TEST'] = 'new value';
}

$arr = array(0 => array ('TEST' => 'foo'));

array_map('callback', $arr);

print_r($arr);

Expected result:
----------------
Array ( [0] => Array ( [TEST] => new value ) )

Actual result:
--------------
Array ( [0] => Array ( [TEST] => foo ) )

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-04-06 17:02 UTC] bjori@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

function callback(&$val) {
    if(!is_array($val)) {
        $val = 'new value';
        return $val;
    } else {
        $ret = array_map('callback', $val);
        return $ret;
    }
}

$arr = array(0 => array ('TEST' => 'foo'));
$arr = array_map('callback', $arr);
print_r($arr);
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu May 23 05:01:31 2024 UTC