Passing POST array to php function

Is it possible to pass the entire POST array to a function and process it inside the function?

such as

PostInfo($_POST); function PostInfo($_POST){ $item1 = $_POST[0]; $item2 = $_POST[1]; $item3 = $_POST[2]; //do something return $result; } 

or is this the right way to do this?

+4
source share
3 answers

Yes. If you are going to name the local variable $_POST , do not worry. $_POST is a "superglobal" global that does not require the global to use outside the normal scope. Your above function will work without a parameter on it.

NOTE You cannot use superglobal (i.e. $_POST ) as a function argument in PHP 5.4 or later. This will result in a fatal error.

+7
source

In fact, you can pass $ _POST to any function that takes in an array.

 function process(array $request) { } process($_POST); process($_GET); 

Great for testing.

+6
source

$_POST -array is an array, like any other array in PHP (besides the so-called superglobal ), so you can pass it as a parameter to a function, pass it and even change it (although in most situations this may be unreasonable).

As for your code, I would modify it a bit to make it more understandable:

 PostInfo($_POST); function PostInfo($postVars) { $item1 = $postVars[0]; $item2 = $postVars[1]; $item3 = $postVars[2]; //do something return $result; } 

This will explicitly separate the function argument from the $_POST superglobal. Another option would be to simply remove the function argument and rely on the super _ global capabilities of $_POST :

 PostInfo(); function PostInfo() { $item1 = $_POST[0]; $item2 = $_POST[1]; $item3 = $_POST[2]; //do something return $result; } 
+1
source

All Articles