Web Analytics

PHP Functions Basics

Beginner~25 min read

Functions are reusable blocks of code that perform specific tasks. They help you organize code, avoid repetition, and make your programs more maintainable. Let's master PHP functions!

What is a Function?

A function is a named block of code that can be called multiple times. Think of it as a recipe - you define it once and use it whenever needed.

Output
Click Run to execute your code

Defining a Function

<?php
function greet() {
    echo "Hello, World!";
}

// Call the function
greet();  // Output: Hello, World!
?>

Function with Parameters

<?php
function greetUser($name) {
    echo "Hello, $name!";
}

greetUser("Alice");  // Hello, Alice!
greetUser("Bob");    // Hello, Bob!
?>

Return Values

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

$result = add(5, 3);
echo $result;  // 8
?>

Summary

  • Define: function name() { }
  • Call: name()
  • Parameters: Input values
  • Return: Output value

What's Next?

Now let's explore Function Parameters in depth - default values, type hints, and more!