CodeBlanks Logo Icon CodeBlanks

Functions with parameters

PHP course · Beginner · Lesson 77/116

Learn to pass parameters to a function and use them inside.

What is a parameter?

A parameter is a variable listed in the parentheses of a function definition. When the function is called, the value from the call (the argument) is copied into this variable and used in the body.

Example: function greet($name) { echo "Hello " . $name; }. Here $name is the parameter. The call greet("Alex") puts "Alex" into $name and prints "Hello Alex". Parameters make a function reusable with different data.

Using a parameter and passing arguments

A parameter is used inside the body like any variable. Its value comes from the argument at the call and can differ each time.

For example in function greet($name) { echo "Hello " . $name . "\n"; } the $name parameter is used for string concatenation. The call greet("Alex") prints "Hello Alex"; greet("Sam") prints "Hello Sam". The same function is reused with different arguments.

Exercise Print a greeting message

Define a function greet with a $name parameter. In the body write echo "Hello " . $name . "\n";. Then call the function once with greet("Alex").

Show example solution
Define with function greet($name) { ... }, put echo "Hello " . $name . "\n"; in the body, then call with greet("Alex");.
Example solution:
<?php
// Define greet and call it
function greet($name) {
    echo "Hello " . $name . "\n";
}
greet("Alex");

Test yourself

  1. Which is a valid function definition with a parameter?

    • function greet() { ... }
    • function greet($name) { ... }
    • function greet(name) { ... }
    • function greet($name;) { ... }
    Show answer

    function greet($name) { ... } — Correct. $name is a parameter; it starts with $ inside the parentheses.

  2. Complete the parameter name

    function greet(____) { echo "Hello " . $name; }
    Show answer
    function greet($name) { echo "Hello " . $name; }
  3. Match parameter and argument concepts

    Parameter
    Variable listed in the definition
    Argument
    Value passed at the call
    $name
    Example of a parameter

All lessons in Beginner