Retrieve value from a n-dimensional array by dynamic index

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ranj1729
Forum Newbie
Posts: 2
Joined: Wed Oct 07, 2009 11:02 pm

Retrieve value from a n-dimensional array by dynamic index

Post 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
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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.
ranj1729
Forum Newbie
Posts: 2
Joined: Wed Oct 07, 2009 11:02 pm

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

Post 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;
 
 
 
Post Reply