HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Function Arguments

Arguments (often called parameters) allow you to pass information into a function. An argument is just like a variable that is defined in the parentheses after the function name.


1. Simple Arguments

Arguments are specified inside the parentheses. You can add as many as you want, separated by commas.

<?php
    function familyName($fname) {
        echo "$fname Refsnes.<br>";
    }

    familyName("Jani");  // Outputs: Jani Refsnes.
    familyName("Hege");  // Outputs: Hege Refsnes.
?>

2. Multiple Arguments

A function can take multiple pieces of information at once to perform complex calculations or operations.

<?php
    function familyName($fname, $year) {
        echo "$fname Refsnes. Born in $year <br>";
    }

    familyName("Hege", "1975");
    familyName("Stale", "1978");
?>

3. Default Argument Value

You can specify a default value for an argument. If the function is called without a value, the default will be used automatically.

<?php
    function setHeight($minheight = 50) {
        echo "The height is : $minheight <br>";
    }

    setHeight(350);
    setHeight(); // Will use the default value of 50
?>
Technical Detail: If you have multiple arguments and only some are optional, the arguments with default values must be placed at the end of the parameter list.

4. Passing Arguments by Reference

By default, function arguments are passed by **value** (a copy). To allow a function to modify its original variable, you must pass the argument by reference using the & symbol.

<?php
    function add_five(&$value) {
        $value += 5;
    }

    $num = 2;
    add_five($num);
    echo $num; // Outputs: 7 (The original variable was changed!)
?>
Pro Tip: Use default values for arguments like "language" or "currency" in your functions to make your code more flexible while remaining easy to call.

Key Points to Remember

  • Arguments are variables defined inside the function's parentheses.
  • You can pass any number of arguments to a single function.
  • Default values provide a fallback if no data is passed during the call.
  • Use the & (reference) operator to let a function modify the original variable.
  • Arguments make functions truly dynamic and powerful.