PHP Functions Example

Define and call your own PHP functions with typed parameters and defaults. Edit the code below and press Run to execute it with real PHP in your browser.

Code Editor
Output
Hello, Alice!
Welcome, Bob!
Sum: 30
42

How this functions example works

A function is declared with function, a name, parameters and an optional return type. Parameters can have default values ($greeting = "Hello") and type declarations. Arrow functions (fn) are short anonymous functions that are handy as callbacks for array_map() and array_filter().

Named arguments (PHP 8.0+)

<?php
function makeTag(string $text, string $tag = "p", string $class = ""): string {
    $attr = $class !== "" ? " class=\"$class\"" : "";
    return "<$tag$attr>$text</$tag>";
}
echo makeTag("Hi", class: "note");

Output:

<p class="note">Hi</p>