Using Multiple Arguments To A Function With parse_str() In PHP

Sending multiple arguments to a function can be done using a parameter string. This is just like a URL that has data encoded into it. For example, if you wanted to send two parameters (called parameter1 and parameter2) to a function then you would use the following string.

parameter1=value1&parameter2=value2

To use this in the function you create the function as normal with a single parameter. This single parameter is the string that will contain all of your arguments.

function test($arguments)
{
}

You must run the parse_str() function on the arguments parameter to extract the data you need. You can then call the parameters by their names as variables.

function test($arguments)
{
 parse_str($arguments);
 if ( isset($parameter1) ) {
  echo $parameter1;
 }
 if ( isset($parameter2) ) {
  echo $parameter2;
 }
}

Note that it is still prudent to check to see that the variable has been created before trying to use it. Otherwise the following error will be produced (if you have error reporting turned on to a high level).

Notice: Undefined variable: parameter2 in test.php on line 5

If you want to send an array of information to the function then just include square brackets. The following function will create an array of two items, as well as our two parameters.

parameter1=value1&parameter2=value2&parameter3[]=value3&parameter3[]=value4

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
6 + 10 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.