How to pass javascript jQuery variable value in php array?

Learning PHP: Is there a way to get the value of multi-dimensional array by specifying the key with a variable?

  • $array = array( 'a' => array( 'a' => "a aaa", 'b' => "b bbb", 'c' => "c ccc", 'd' => "d ddd", ), 'b' => array( 'a' => "b aaa", 'b' => "b bbb", 'c' => "c ccc", ), ); echo '<pre>' . print_r( $array, true ) . '</pre>'; When there is an array like the above and if I want to retrieve one of the values, for example, echo $array['a']['b']; would work. I'm wondering if there is a way to specify the key with a variable. I mean I want my users to specify a key of multidimensional array and pass them the value of it. This does not work. $key = '["a"]["b"]'; echo $array{$key};

  • Answer:

    If you have a very specific array structure, you can just make a function to do the parsing for you.  Something like: <?php $array = array( 'a' => array( 'a' => 'a aaa', 'b' => 'b bbb', 'c' => 'c ccc', 'd' => 'd ddd', ), 'b' => array( 'a' => "b aaa", 'b' => "b bbb", 'c' => "c ccc", ), ); echo '<pre>' . print_r( $array, true ) . '</pre><br /><br />'; $key = '["a"]["b"]'; function getArrayValue($array, $key) { $key = preg_match("/\[['\"]{1}(.+)['\"]{1}\]\[['\"]{1}(.+)['\"]{1}\]/", $key, $matches); if (count($matches) !== 3) { return NULL; } $first = $matches[1]; $second = $matches[2]; return $array[$first][$second]; } echo getArrayValue($array, $key); ?> Note: If you want to support any number of dimensions, just use explode() and a loop to read each individual key and get the next sub array. However, whatever you're trying to do doesn't sound like very good design.  The customer's perspective of your program should be at a verify abstract level.  Most likely, whatever you're doing can be abstracted away from the underlying data structures (and should be).

John Kurlak at Quora Visit the source

Was this solution helpful to you?

Other answers

If you have the keys as an array, then it is easy to write a function that does this: function multiArrayAccess($array, $keys) { $result = $array; foreach ($keys as $key) $result = $result[$key]; return $result; } echo multiArrayAccess($array, array('a', 'b')); or even function multiArrayAccess($array, $keys) { return array_reduce($keys, function($x, $key) { return $x[$key]; }, $array); } echo multiArrayAccess($array, array('a', 'b'));

Xuan Luo

No, there is not. This being PHP, you could do crazy things like eval('$array' . $key);, but that isn't good. However, you could let your user given an array of two keys, then use $array[$key[0]][$key[1]].

Jelle Zijlstra

I agree with John, there's probably a better way of thinking about this that carries more abstraction and is more flexible. e.g. if you really need to store a pair of keys for one array as a separate variable, how about just make that another array: <?php $address = array( 'level1' => 'a', 'level2' => 'b' ); $result = $array[$address['level1']][$address['level2']]; echo $result;

Adam Marshall

Yes, you can directly get the array value by using a variable. foreach ($array as $key=>$val) { print_r($val); print_r($array[$key]); } In your example, here is how you could access the value of the array at index ["a"]["b"] $a = "a"; $b = "b"; print_r($array[$a][$b]);

Jared Eckersley

The answer is that, yes yes yes you can do it, using recursion (sadly not much people here know algorithms and CS basics well, so I don’t think anyone here has the correct answer). Therefore, what J said is terribly wrong.You can access a specific value of a multidimentional array using specified variables as keys, when knowing its depth (which you can find using another custom-made function discussed in http://stackoverflow.com/questions/262891/is-there-a-way-to-find-out-how-deep-a-php-array-is (via Stack Overflow) The mechanism involved in finding the depth is also recursion). I had to face this problem today when trying to make a flexible web-based playground for my RESTful API, where I allow authenticated users to make custom cURL GET requests.Let’s just see the code. (This is just a crappy example I coded up in <10mins, could have bugs and can be optimized. Never use this in production without understanding it) /** * Access a specific member of an multidimensional array * given $keys as a series of keys. * @author Alexxonderros Fannggovitch * @param $array array the array to be accessed * @param $keys array a series of keys, the first one for the * top level, the second one for the second level, etc * @param $depth integer how deep the multidimensional array is */ function accessArray($array, $keys, $depth) { if($depth > 1) { return accessArray( $array[$keys[count($keys) - ($depth)]], $keys, ($depth - 1)); } else { for($i = 0; $i < count($array); $i++) { //traverse if((count($array) - 1) == $i) { return $array[$keys[$i]]; } } } } Usage example: var_dump(accessArray([ "hi" ], [0], 1)); Which will output: string(2) "hi" Note that the keys array should be a series of values for each dimension of the keys. E.g. $keys = [ "animal", "dog", "great dane", "size" ]; matched up with $array = [ "animal" => [ "dog" => [ "great dane" => [ "size" => "big" ] ] ], "alien" => "no no no", "computer" => [ "linux" ] ]; will produce the result string(3) "big" Some extended reading: https://en.wikipedia.org/wiki/Recursion (from Wikipedia).

Alexxonderros Fannggovitch

$key = '["a"]["b"]'; echo $array{$key} will not and should not work.This will work, but I’m not clear on exactly what you’re trying to do, so this may not be the best answer either: $one = $_REQUEST["user_input_value_for_a"]; $two = $_REQUEST["user_input_value_for_b"]; print_r($array['a']["${one}"] .' '.$array['b']["{$two}"]); More than likely, John or Alexxonderros answers below are a better fit, but given the limited context here, wanted to present you with a third, simpler alternative just in case. Also note that if you do find the above to fit what you need, you’ll still need to add some form of error handling.But more to the point, although your goal here isn’t totally clear to me, I think that you are making this more complex than it needs to be. Give us more context and we can see if there’s improvements to be had.

Andrew Rout

Quite Simple: <?php // The Array $array = array( 'a' => array( 'a' => "a aaa", 'b' => "b bbb", 'c' => "c ccc", 'd' => "d ddd", ), 'b' => array( 'a' => "b aaa", 'b' => "b bbb", 'c' => "c ccc", ), ); // Lets see a specific key ( e.g. $array['b']['c']) $key_one = 'b'; $key_two = 'c'; // Spew. Expecting 'c ccc'; echo $array[$key_one][$key_two]; ?>

Leonard Cooper

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.