How to extract POST data in one line with php : extract($_POST);

Here is a quick trick in php that can save you time when you retrieve data from an html form.

Lets say you normally have a form with name, surname, email and telephone number.

You would normally collect those informations in your script as such:


$name = $_POST['name'];
$surname = $_POST ['surname'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];

Then you just use your variables in your php script. But things tend to be more complicated when you have more variables in your forms.

Just imagine that you have a questionnaire of about 50 questions, meaning you would have to write 50 lines of php codes just to get those variables.

The trick here is to use the build in php function extract. It would automatically extract the values and assign it to a variable with the key as its name.

I.e. value in $_POST['something'] would be passed in the variable called $something.

So for the example given above the code would be simplified in only one php line to:

  extract($_POST);

It sure save times if you have many variables, even for 2 it is effective. If you ever add another variable to your html form, you don't need to add another line of code to retrieve the value. This can also be used with $_GET also.

0 comments:

Post a Comment