Accessing Array Values with a variable key

From last few days I have been trying to figure out how to access an array value in PHP using a key value that is stored in a string. So finally i was able to frame a function that could just do that.
Following is the code to get a value from an array with known key
Here
`$arr = Array with values
$key = string with keys seperated with –

function get_array_val($arr,$key)
{
	$e= explode('-',$key);
	$ar = &$arr;
	foreach($e as $v)
		$ar = $ar[$v];
	unset($ar);
	return $arr;
	
}


Example Call

echo get_array_val($fruit,"0-1");

Following is the code to set a value from to array with known key
Here
`$arr = Array with values
$key = string with keys seperated with –
$val = anything that you want to store to that location.

function set_array_val($arr,$key,$val)
{
	$e= explode('-',$key);
	$ar = &$arr;
	foreach($e as $v)
		$ar = &$ar[$v];
	$ar = $val;
	unset($ar);
	return $arr;
	
}

For Example if following are my array

$fruit = array ( "0"  => array ( "a" => "orange",
                                       "b" => "banana",
                                       "1" => "apple"
                                     ),
                  "1" => array ( "a" => "orange",
                                       "b" => "banana",
                                       "c" => "apple"
                                     ),
                  "2"   => array (      "first",
                                       5 => "second",
                                            "third"
                                     )
                );

Then ,

Code : echo get_array_val($fruit,"0-1");
Outputs: apple

And,

$f = set_array_val($fruit,"0-1",array('a'=>'ginger','vc'=>'potato'));
echo get_array_val($f,"0-1-vc");
Outputs:
potato

Let me know if there is an issue

Advertisements
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: