Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a deep array in PHP

Tags:

php

Assume I have the following function

function setArray(&$array, $key, $value)
{
    $array[$key] = $value;     
}

In the above function, key is only at the first level, what if I want to set the key at the 2nd or 3rd levels, how to rewrite the function?

e.g.

 $array['foo']['bar'] = 'test';

I want to use the same function to set the array value

like image 201
Ryan Avatar asked Nov 13 '12 10:11

Ryan


1 Answers

This one should work. Using this function you can set any array element in any depth by passing a single string containing the keys separated by .

function setArray(&$array, $keys, $value) {
  $keys = explode(".", $keys);
  $current = &$array;
  foreach($keys as $key) {
    $current = &$current[$key];
  }
  $current = $value;
}

You can use this as follows:

$array = Array();
setArray($array, "key", Array('value' => 2));
setArray($array, "key.test.value", 3);
print_r($array);

output:

Array (
    [key] => Array
        (
            [value] => 2
            [test] => Array
                (
                    [value] => 3
                )

        )

)
like image 149
MarcDefiant Avatar answered Oct 29 '22 13:10

MarcDefiant