Multiple parameters
Learn to define multiple parameters and call them in order.
Multiple parameters
A function can take multiple parameters. Parameters are separated by commas inside the parentheses and each has its own name.
Example: function formatName($first, $last) { return $first . " " . $last; }. There are two parameters: $first and $last. Arguments match in order: in formatName("Alex", "Brown") "Alex" goes to $first and "Brown" to $last.
Parameter order matters
Arguments match parameters by position: the first argument goes to the first parameter, the second to the second. Wrong order gives a wrong result.
For example in function divide($a, $b) { return $a / $b; } the call divide(10, 2) returns 5; but divide(2, 10) returns 0.2. With positional parameters, always check which argument lands in which parameter.
Exercise Join first and last name
Define a function formatName with parameters $first and $last. In the body write return $first . " " . $last;. Then print the result with echo formatName("Alex", "Brown") . "\n";.
Show example solution
Define function formatName($first, $last) { ... }, put return $first . " " . $last; in the body, then call with echo formatName("Alex", "Brown") . "\n";.
Example solution:
<?php
// Define formatName and call it
function formatName($first, $last) {
return $first . " " . $last;
}
echo formatName("Alex", "Brown") . "\n";
Test yourself
-
Complete the two-parameter function
function add(____) { return $a + $b; }Show answer
function add($a, $b) { return $a + $b; } -
What is the output of the following code?
function formatName($first, $last) { return $first . " " . $last; } echo formatName("Alex", "Brown");- Alex Brown
- Brown Alex
- AlexBrown
- Alex, Brown
Show answer
Alex Brown — Correct. The first argument goes to $first and the second to $last.
-
Match multi-parameter concepts
- Comma
- Separates parameters
- Order
- Arguments match parameters in order
- formatName($first, $last)
- Two-parameter function