How can I use array references inside arrays in PHP?

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

Hi

/R

+3
source share
5 answers

end()does not return the link of the last value, but the most recent value. 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];
}
+4
source

Here are a few approaches, none of which I find particularly satisfactory. I am sure there is a better way.

<?php
$normal_array       = array();
$array_of_arrayrefs = array( "blah", &$normal_array );

foreach ($array_of_arrayrefs as &$v);
$v["one"] = 1;

echo $normal_array["one"];  //prints 1
?>


<?php
$normal_array       = array();
$array_of_arrayrefs = array( "blah", &$normal_array );

$lastIndex = @end(array_keys($array_of_arrayrefs)); //raises E_STRICT because end() expects referable.
$array_of_arrayrefs[$lastIndex]["one"] = 1;

echo $normal_array["one"];  //prints 1
?>
+1
source

, , . , .

, . - , , , . PHP copy-on-write, , , .

, , PHP4, . PHP5.

+1

end() . . key() , .

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

end($array_of_arrayrefs);
$array_of_arrayrefs[ key($array_of_arrayrefs) ]["one"] = 1;

print $normal_array["one"];
0

:

end ($ array_of_arrayrefs) [ "one" ] = 1;//

:

: , '[' /file.php 65

, error_reporting display_error.

, , :

$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?
$array_of_arrayrefs[0]["one"] = 1;
//end($array_of_arrayrefs )["one"] = 1; // choking on this one
print $normal_array["one"]; // should output 1
-1

Source: https://habr.com/ru/post/1698152/


All Articles