Page 1 of 1

Retrieve value from a n-dimensional array by dynamic index

Posted: Wed Oct 07, 2009 11:05 pm
by ranj1729
I have a n dimensional array, and I want to retrieve array value using other variable,
Example: Suppose $a is a 5 dimensional array. I want to get values of $a[3][4], where '3_4' is coming as a parameter string. If parameter be 1_2_3 then that means I want to retrieve or change value of $a[1][2][3]. If parameter be 1_2_3_1 then that means I want to retrieve or change value of $a[1][2][3][1].

Please help me how to achieve this using PHP.

Thanks with Regards,

Ranjit Paul,
Limtex, Kolkata

Re: Retrieve value from a n-dimensional array by dynamic index

Posted: Wed Oct 07, 2009 11:20 pm
by requinix

Code: Select all

$array = array(/* ... */);
$parameters = explode("_", "1_2_3_4");
 
$a = $array;
foreach ($parameters as $offset) {
    if (!isset($a[$offset])) break; // bad parameter
    $a = $a[$offset];
}
$a is the result.

Re: Retrieve value from a n-dimensional array by dynamic index

Posted: Fri Oct 09, 2009 4:17 pm
by ranj1729
hi tasairis,
thanks for your reply
to change the value of the index position

Code would be something like:

Code: Select all

 
    $array = array(/* ... */);
    $parameters = explode("_", "1_2_3_4");
     
    $a =& $array;
    foreach ($parameters as $offset) {
       if (!isset($a[$offset])) break; // bad parameter
      $a = &$a[$offset];
    }
    $a = $value_to_set;