PHP Functions

Functions are one of the most powerful features in PHP. They allow you to organize code into reusable blocks, making your programs more modular and readable. In PHP, a function is defined using the function keyword, followed by a name, parentheses (), and a block of code {}.

🔹 Why Use Functions?

  • Code Reusability – Write once, use multiple times.
  • Better Organization – Break complex logic into smaller, manageable pieces.
  • Easier Maintenance – Fix bugs or update logic in one place.

📝 Example 1: Defining and Calling a Function

Here’s a simple example of a function in PHP:

<?php
function greet() {
    echo "Hello, welcome to PHP functions!";
}

greet(); // Call the function
?>

Try It Now

Explanation:

  • The function greet() is defined using the function keyword.
  • Inside the function, echo prints a message.
  • Calling greet(); executes the function and displays the message.

📝 Example 2: Function with Parameters

Functions can accept parameters to make them more dynamic.

<?php
function greetUser($name) {
    echo "Hello, $name! Welcome to PHP functions.";
}

greetUser("Alice"); // Call the function with an argument
?>

Try It Now

Explanation:

  • The function greetUser($name) takes one parameter $name.
  • When called with "Alice", it prints "Hello, Alice! Welcome to PHP functions.".

📝 Example 3: Function with Return Value

A function can return a value using the return statement.

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

$result = add(5, 7);
echo "Sum: $result";
?>

Try It Now

Explanation:

  • The function add($a, $b) returns the sum of two numbers.
  • The result is stored in $result and printed.

📝 Example 4: Default Parameter Values

You can set default values for parameters.

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

greetPerson(); // Uses default value
greetPerson("Bob"); // Overrides the default value
?>

Try It Now

Explanation:

  • If no argument is passed, $name defaults to "Guest".
  • If an argument is provided, it overrides the default value.

🎯 Summary

  • Functions help break down complex programs into reusable blocks.
  • Use parameters to make functions flexible.
  • return allows functions to send back a value.
  • Default values make functions more adaptable.

📝 Practice Time!

Modify the examples and experiment with different values to understand how PHP functions work!