Jean
Jean

Reputation: 59

PHP make a multidimensional associative array from key names

Even if it's documented, I need help to better understand this code (only references). I already checked tutorials, but they didn't help me.

// initialize variables
$val = 'it works !';
$arr = [];

// Get the keys we want to assign
$keys = [ 'key_1', 'key_2', 'key_3', 'key_4' ];

// Get a reference to where we start
$curr = &$arr;

// Loops over keys
foreach($keys as $key) {
   // get the reference for this key
   $curr = &$curr[$key];
}

// Assign the value to our last reference
$curr = $val;

// visualize the output, so we know its right
var_dump($arr);
echo "<hr><pre>\$arr : "; print_r($arr);

(Source : https://stackoverflow.com/a/31103901/4741362 @Derokorian)

Upvotes: 0

Views: 405

Answers (1)

Umer Abbas
Umer Abbas

Reputation: 1876

I'll try to explain it for you to understand it a little better, see the working code here. I hope it helps you understand this $curr = &$curr[$key]; line. $curr points to the empty $arr before the foreach starts, In foreach it saves the value of $key into the $arr by reference which was pointed by $curr and then reassigns the reference of the newly saved $key in $arr to the $curr pointer again.

// initialize variables
$val = 'it works !';
$arr = [];

// Get the keys we want to assign
$keys = [ 'key_1', 'key_2', 'key_3', 'key_4' ];

// Get a reference to where we start
echo "create a space where to save the first key \r\n";
$curr = &$arr;

// Loops over keys
$i = 1;
foreach($keys as $key) {

    echo "**************** Iteration no $i ******************\r\n";
    // echo "save the value \"$key\" to the reference created earlier in the \$curr variable for the empty array above where the kesy are actually being saved \r\n";

    // get the reference for this key
    echo "Now save the value of \$key to the array reference present in \$curr and then assigne the reference of newly saved array item to \$curr again \r\n";
    $curr = &$curr[$key];
    print_r($arr);

   $i++;
   echo "\r\n\r\n";
}

// Assign the value to our last reference
$curr = $val;

// visualize the output, so we know its right
print_r($arr);

Upvotes: 1

Related Questions