Search code examples
phparraysreferencepass-by-reference

Set element on last reference in an array of references


I want to be able to do the following:

$normal_array       = array();
$array_of_arrayrefs = array(&$normal_array);

// Here I want to access the $normal_array reference **as a reference**,
// but that doesn't work obviously. How to do it?
end($array_of_arrayrefs)["one"] = 1; // choking on this one

print $normal_array["one"]; // should output 1

Solution

  • end() doesn't return a reference of the last value, but rather the last value itself. Here is a workaround:

    $normal_array       = array();
    $array_of_arrayrefs = array( &$normal_array );
    
    $refArray = &end_byref( $array_of_arrayrefs );
    $refArray["one"] = 1;
    
    print $normal_array["one"]; // should output 1
    
    function &end_byref( &$array ) {
        $lastKey = end(array_keys($array));
        end($array);
        return $array[$lastKey];
    }