๐ŸŽ“ A1Learner
๐Ÿ”

PHP Function Arguments

Function arguments are values passed to a function in a call. A parameter is a variable in the definition that receives one of those values.

One parameter

The greet function takes one parameter, $name. The call passes the text Hana as the argument.

<?php
function greet($name) {
  echo "Hello $name\n";
}

greet("Hana");

Two parameters

The greetFull function takes two parameters. The call passes two arguments in the same order.

<?php
function greetFull($name, $city) {
  echo "Hello $name from $city\n";
}

greetFull("Hana", "Oslo");

A value sent back

The add function sends its sum back with return. The caller saves the value in $total and prints it.

<?php
function add($a, $b) {
  return $a + $b;
}

$total = add(4, 3);
echo "$total\n";

A default value

The parameter $name has the default value guest. The first call passes nothing, and the second call passes Hana.

<?php
function greet($name = "guest") {
  echo "Hello $name\n";
}

greet();
greet("Hana");

An array sent back

The sumAndProduct function sends back one array with two numbers. The caller reads the parts by index.

<?php
function sumAndProduct($a, $b) {
  return [$a + $b, $a * $b];
}

$pair = sumAndProduct(4, 3);
echo $pair[0] . "\n";
echo $pair[1] . "\n";

Example

<?php
function area($width, $height) {
  return $width * $height;
}

echo area(5, 3) . "\n";
echo area(4, 6) . "\n";

Key points

  • Arguments fill the parameters in order, from first to last.
  • A function can take one parameter, many parameters, or none.
  • The return word sends a value back to the code that made the call.
  • A default value is written after an equals sign in a parameter.
  • A call that leaves an argument out gets the default value for that parameter.
  • A function can return an array as one value.

In this example, area takes a width and a height. It sends back the product of the two values. The first call prints 15, and the second call prints 24.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz PHP Compiler

Exercise

A parameter has a default value. What happens when a call leaves that argument out?