PHP function array_replace (), why are arguments passed by reference?

The PHP.net function signature for array_replace () says the arrays will be passed by reference. What would be the reason (s) / benefit in doing it this way, and not by value, since in order to get the intended result you have to return the finished array to the variable. To be clear, I can reproduce the results in the manual, so it is not a question of how to use this function.

Here is the function signature and example, as from php.net.

Source: http://ca3.php.net/manual/en/function.array-replace.php

Functional Signature:

array array_replace ( array &$array , array &$array1 [, array &$... ] )

Code example:

$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");

$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);

The above example outputs:

Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)
+5
source share
4 answers

, php_array_merge_or_replace_wrapper, zend_hash_merge, _ zend_hash_merge .. .. .. memcmp(), , , , PHP array_replace() ( memcmp() , ).

- PHP, , , , , .

+4

, , _ zend_hash_merge array_merge - + operator ( ).

, : , + &$arr + &$arr, .

, .

, PHP. ) , &$array, , (, , ) - ​​., , array_splice() . ( ) array_replace - , . )

: , . - PHP-, , , , / , :

array_pop(array('a' => 1));

... (Only variables can be passed by reference), ...

array_replace(array('a' => 1), array('b' => 2));

... , .

PHP ?

+3
source

Hypothesis:

Since passing by value involves copying the array, I think it's faster to pass them by reference.

check it out:

<?php 

function ref(array &$array) {
    for($i = 0; $i < count($array); $i++) {
        $array[$i] == 'foo'; //just accessing
    }
}

function val(array $array) {
    for($i = 0; $i < count($array); $i++) {
        $array[$i] == 'foo'; //just accessing
    }
}


//create large array
$array = array();
for($i = 0; $i < 100; $i++) {
    $array[] = $i;
}


echo "Pass by reference\n";
$t1 = microtime(true);
for($i = 0; $i < 10000; $i++) {
    ref($array);
}
$t2 = microtime(true);
echo $t2 - $t1 . "s\n\n";

echo "Pass by value\n";
$t1 = microtime(true);
for($i = 0; $i < 10000; $i++) {
    val($array);
}
$t2 = microtime(true);
echo $t2 - $t1 . "s\n\n";

outputs:

Pass by reference
8.3282010555267s

Pass by value
1.4845979213715s

Conclusion:

Obviously, this is not for performance reasons.

+1
source

All Articles