All categories
    PHPIntermediate

    PHP Functions

    Define functions in PHP: parameters and return values, default arguments, arrow functions, and recursion with examples.

    01Define a function

    main.php
    <?php
    function greet($name) {
        return "Hello, $name!";
    }
    echo greet("World"), "\n";
    Output
    Hello, World!

    02Default parameters

    main.php
    <?php
    function power($base, $exp = 2) {
        return $base ** $exp;
    }
    echo power(5), "\n";
    echo power(2, 10), "\n";
    Output
    25
    1024

    03Arrow function

    main.php
    <?php
    $square = fn($x) => $x * $x;
    echo $square(6), "\n";
    Output
    36

    04Recursion (factorial)

    main.php
    <?php
    function factorial($n) {
        if ($n <= 1) return 1;
        return $n * factorial($n - 1);
    }
    echo factorial(5), "\n";
    Output
    120