How can i pass multiple variables to a function in php?

Apologies for the newbie question but i have a function that takes two parameters one is an array one is a variable function createList($array, $var) {}. I have another function which calls createList with only one parameter, the $var, doSomething($var); it does not contain a local copy of the array. How can I just pass in one parameter to a function which expects two in PHP?

attempt at solution :

function createList (array $args = array()) {
    //how do i define the array without iterating through it?
 $args += $array; 
 $args += $var;


}

asked May 29, 2013 at 20:54

0

If you can get your hands on PHP 5.6+, there's a new syntax for variable arguments: the ellipsis keyword.
It simply converts all the arguments to an array.

function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}
echo sum(1, 2, 3, 4);

Doc: ... in PHP 5.6+

answered Nov 21, 2014 at 14:35

How can i pass multiple variables to a function in php?

PetruzaPetruza

11.3k24 gold badges81 silver badges131 bronze badges

1

You have a couple of options here.

First is to use optional parameters.

  function myFunction($needThis, $needThisToo, $optional=null) {
    /** do something cool **/
  }

The other way is just to avoid naming any parameters (this method is not preferred because editors can't hint at anything and there is no documentation in the method signature).

 function myFunction() {
      $args = func_get_args();

      /** now you can access these as $args[0], $args[1] **/
 }

answered May 29, 2013 at 21:00

OrangepillOrangepill

24.4k3 gold badges40 silver badges63 bronze badges

1

You can specify no parameters in your function declaration, then use PHP's func_get_arg or func_get_args to get the arguments.

function createList() {
   $arg1 = func_get_arg(0);
   //Do some type checking to see which argument it is.
   //check if there is another argument with func_num_args.
   //Do something with the second arg.
}

answered May 29, 2013 at 20:59

crushcrush

16.5k8 gold badges57 silver badges100 bronze badges

At some point in your PHP development you are likely to want to break repeated functionality out into a separate, well, function. Something that you’ll no doubt also want to do is pass information back and forward from these functions.

If you are familiar with scope in programming you will be aware that variables are typically only available where they are created. This means if you create a variable called $name in the main part of your code you would not be able to “see” this variable in a function unless you passed it across. The scope of the variable is limited.

In many languages there is the concept of a global scope that allows you to make a variable available globally so you would be able to access it anywhere. This is frowned upon in PHP so how do you get variables in and out of functions? In the rest of this article I show you through a number of different examples.

Passing No Parameters

In this simple example we have a function called get_user that will eventually return user information. Here we are passing no parameters and all the function does is print out the words ‘hello world!’.

This is not particularly useful but does illustrate the concept.

function get_user(){
    echo 'hello world!';
}

get_user();

This would output:

hello world!

Passing One or More Parameter

Next we want to pass in one or more parameter which we do by including the name in the brackets after the function name. It is important to note that these names are what they are referred to in the function and not in the calling code.

function get_user($firstname, $lastname){
    echo 'hello ;.$firstname.' '.$lastname;
}
get_user('Neil', 'Thompson');

Running this would output:

hello Neil Thompson

Setting Defaults for Passed Parameters

It is also possible to set default parameters for variables that you are passing into a function. These can also be null if you wanted.

function get_user($firstname='Fred', $lastname='Bloggs'){
    echo 'hello ;.$firstname.' '.$lastname;
}
get_user('Neil', 'Thompson');
get_user();

Running this would output:

hello Neil Thompson
hello Fred Bloggs

Returning a Single Response

So you have passed in some parameters but how do you get something out? For that you need to use the return statement which returns control to whatever called the function.

You don’t need to return anything but if you need to then you do so immediately after the return statement as shown below. Important note you can return one and only one item which seems a bit restrictive but we’ll get to that below.

function get_user($firstname='Fred', $lastname='Bloggs'){
    return ucwords($firstname.' '.$lastname);
}
$response = get_user('neil', 'thompson');
echo $response;

Running this would output:

Neil Thompson

Returning Multiple Responses #1

One of the restrictions of the return statement is that you can return one and only one variable. On the face of it this seems pretty limiting but there are ways around this. The first is to return an array or even an array of arrays and unpack that. For example:

function get_user($firstname='Fred', $lastname='Bloggs'){

    $response = array('first'=> ucwords($firstname), 'last'=>ucwords($lastname));
    return $response;
}
$response = get_user('neil', 'thompson');
print_r($response);

Running this would output:

Array (     
  [first] => Neil
  [last] => Thompson
)

A slightly more complicated example with nested arrays:

function get_user($firstname='Fred', $lastname='Bloggs'){

    $response = array('proper' => array('first'=> ucwords($firstname), 'last'=> ucwords($lastname)),
                      'upper' => array('first'=> strtoupper($firstname), 'last'=> strtoupper($lastname)));
    return $response;
}
$response = get_user('neil', 'thompson');
print_r($response['upper']);
$proper = $response['proper'];

Running this would output:

Array (
  [upper] => Array (
    [first] => NEIL
    [last] => THOMPSON
  )
)

Returning Multiple Responses #2

The above example is a bit contrived and there is a better way to deal with these sorts of multiple returns using the not very helpfully named list function. What this effectively does it split out the arrays as shown above into separate variables. Let’s take a look.

function get_user($firstname='Fred', $lastname='Bloggs'){

    $response = array('proper' => array('first'=> ucwords($firstname), 'last'=> ucwords($lastname)),
                      'upper' => array('first'=> strtoupper($firstname), 'last'=> strtoupper($lastname)));
    return $response;
}
list($proper, $upper) = get_user('neil', 'thompson');
print_r($upper);

Running this would output:

Array (
  [upper] => Array (
    [first] => NEIL
    [last] => THOMPSON
  )
)

So in the above snippet the function is returning two arrays which are then separated out by the list command and placed in the two new variables shown.

By combining all the features shown here you should be able to easily pass in and out as many variables to a function as you need. Happy coding!

How pass multiple values in array in PHP?

Create an instance for your view file and use predefined method of a controller file to set variables. Like this way: return new ViewModel(array( 'order_by' => $order_by, 'order' => $order, 'page' => $page, 'paginator' => $paginator, ));

What are the different ways of passing parameters in functions in PHP?

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists and Named Arguments are also supported. As of PHP 8.0. 0, the list of function arguments may include a trailing comma, which will be ignored.

How do you pass multiple values in a function?

The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don't know how many arguments will be sent to the function.

How can I return multiple values from a single function in PHP?

PHP doesn't support to return multiple values in a function. Inside a function when the first return statement is executed, it will direct control back to the calling function and second return statement will never get executed.