Reputation: 177
I need to retrieve an php variable only by knowing it's html input name.
Such as: I know the input's name is admin[username] so I want to get the variable $_POST['admin']['username]
I need this for some sort of validations of the inputs. In other word, I save the html input name when I display the form, but only test it at the next server request, so I don't always know what will be the php variable name, since it can be modified by javascript or I can have array such if the html input name is admin[]
Thank you
Upvotes: 1
Views: 123
Reputation: 7694
$postdata = get_associative_array_from_post_data($post['admin']);
function get_associative_array_from_post_data($array){
if(isAssoc($array)){
/*foreach($array as $key=>$value){
$your_key = $key;
$your_value = $value;
}*/
return $array;
}
else{ //if the post array has no keys, search for arrays within this
$key_collection=array();
foreach($array as $sub_array){
foreach($sub_array as $key=>$value){
$key_collection[$key][] = $value;
}
}
return $key_collection;
}
}
function isAssoc($arr)
{
return array_keys($arr) !== range(0, count($arr) - 1);
}
If you post:
admin[username] = 'test' and admin[email] = '[email protected]'
you will get
$postdata = array('username'=>'test', 'email'=>'[email protected]');
If you post : admin[][username] = 'test' and admin[][username] = 'test2' admin[][email] = '[email protected]' and admin[][email] = '[email protected]'
You will get:
$postdata = array(
'username'=>array('test', 'test2'),
'email'=>array('[email protected]', '[email protected]')
);
Upvotes: 2