If a have a form input with a name like "name[0][firstname]", $_POST will retrieve that as:
'name' => array (size=1) 0 => array (size=9) 'firstname' => null so echo $_POST['name'][0]['firstname'] will give me null.
The question is how can I build the post query dynamically from the array keys? so, for example:
$foo = array('name', 0, 'firstname'); echo $_POST[$foo]; // obviously doesn't work What I need do is build this statement, $_POST['name'][0]['firstname'], from the array but can't find a way to do it. I thought maybe $_POST{'[' . implode('][',$foo) . ']'} might work but I get Undefined index: ['name'][0]['firstname'].
Final solution **
With regards to the solution by @Alireza and @Matteo, both work, except in the case if the array is longer than the $_POST array, eg, if array is $foo = array('name', 0, 'firstname', 'lastname') and the post value is array['name'][0]['firstname'] = "XXX" the result will be "X" which is index 0 of the result XXX. Therefore it needs to check the keys of the post and not the value.
The final solution for me is therefore:
function getValue($res, $foo) { foreach ($foo as $val) { if (is_array($res) && array_key_exists($val, $res)) { $res = $res[$val]; } else { return false; } } return $res; } Examples:
$post = array( 'name' => array( 0 => array( 'firstname' => 'XXX' ), ) ); echo getValue($post, array('name', 0, 'firstname')); > XXX echo getValue($post, array('name', 0, 'firstname', 'lastname')); > false echo getValue($post, array('name', 0, 'firstname', 0)); > false echo getValue($post, array('name', 0, 0)); > false echo getValue($post, array('name', 0)); > Array (eg, Array ( [firstname] => XXX )) - expected Thanks for the help.
echo $_POST[$foo[0]][$foo[1]][$foo[2]];maybe?$_POST[$foo[0]][$foo[1]][$foo[2]];is that what you want ?