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

12th April 2008

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.

  1. function test($arguments)
  2. {
  3. }

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.

  1. function test($arguments)
  2. {
  3. parse_str($arguments);
  4. if ( isset($parameter1) ) {
  5. echo $parameter1;
  6. }
  7. if ( isset($parameter2) ) {
  8. echo $parameter2;
  9. }
  10. }

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.

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

Add new comment

The content of this field is kept private and will not be shown publicly.