开发者

How can I extract the name of a $_POST variable, not its value_

I am building a function that will validate the values in a form. How can I extract the actual name in st开发者_C百科ring form from a $_POST variable? Ex: $_POST['first_name'] = 'Joe';

I now want to grab the string 'first_name' and use it in a function to declare a variable by that name. I know I can use a foreach loop but isn't there an easier way to do this?


How about

extract($_POST);


foreach( $_POST as $key => $value ) {
     $$key = $value;
}


As far as I understood, you are looking for array_keys($_POST).


I'm not sure whether this is what you want, but you can use variable variables like so:

$fieldname = "first_name";

$fieldvalue = $_POST[$fieldname];

$$fieldname = $fieldvalue;   // Creates a variable named "first_name"

echo $first_name;  // Outputs the POST variable


I wouldn't use this:

foreach( $_POST as $key => $value ) {
     $$key = $value;
}

...it opens your code to the possibility of someone maliciously setting vars within your program via the form. (i.e., effectively setting globals_register on)

But to answer your core question: your only knowledge of the posted variables is what's in the $_POST array; your only way of finding out what the variable names are is looping through the array keys.


If you want to execute function based on the key name, your best shot would be something like this:

foreach ($_POST AS $key => $value)
{
    call_user_func("example_func_$key", $value);
}

Note the use of $key within the double-quotes of the first parameter of call_user_func. This will allow you to execute a "dynamically" named-function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜