PHP Functions

Reusable blocks of code that perform specific tasks

๐Ÿ”ง What are PHP Functions?

Functions are reusable blocks of code that perform specific tasks. They help organize code, reduce repetition, and make programs easier to maintain and understand.


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

greet(); // Call the function
?>
                                    

Output:

Hello, World!

Types of Functions

๐Ÿ“ฆ

Built-in Functions

PHP provides thousands of ready-to-use functions for common tasks like string manipulation, math operations, and array handling.

<?php
echo strlen("Hello"); // 5
echo strtoupper("php"); // PHP
?>
โœ๏ธ

User-Defined Functions

Create your own custom functions to perform specific tasks. Define once and reuse throughout your code for better organization.

<?php
function sayHello() {
    echo "Hello!";
}
?>
๐ŸŽฏ

Functions with Parameters

Pass data to functions using parameters. This makes functions flexible and able to work with different values each time.

<?php
function greet($name) {
    echo "Hello, $name!";
}
?>
โ†ฉ๏ธ

Return Values

Functions can return values using the return statement. This allows you to use the result in other parts of your code.

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

๐Ÿ”น Creating Basic Functions

Define a function using the function keyword:

<?php
// Function without parameters
function displayMessage() {
    echo "Welcome to PHP Functions!";
}

// Call the function
displayMessage();
?>

Output:

Welcome to PHP Functions!

๐Ÿ”น Functions with Parameters

Pass information to functions using parameters:

<?php
// Function with one parameter
function greetUser($name) {
    echo "Hello, $name! Welcome back.";
}

greetUser("Alice");
echo "<br>";
greetUser("Bob");
?>

Output:

Hello, Alice! Welcome back.

Hello, Bob! Welcome back.

๐Ÿ”น Multiple Parameters

Functions can accept multiple parameters separated by commas:

<?php
function calculateSum($num1, $num2) {
    $sum = $num1 + $num2;
    echo "$num1 + $num2 = $sum";
}

calculateSum(10, 20);
echo "<br>";
calculateSum(5, 15);
?>

Output:

10 + 20 = 30

5 + 15 = 20

๐Ÿ”น Default Parameter Values

Set default values for parameters if no argument is provided:

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

greetWithTitle("Smith", "Mr.");
echo "<br>";
greetWithTitle("Johnson"); // Uses default "Guest"
?>

Output:

Hello, Mr. Smith!

Hello, Guest Johnson!

๐Ÿ”น Return Values

Use return to send a value back from a function:

<?php
function multiply($a, $b) {
    return $a * $b;
}

$result = multiply(5, 4);
echo "5 ร— 4 = $result";

// Use directly in expressions
echo "<br>";
echo "10 ร— 3 = " . multiply(10, 3);
?>

Output:

5 ร— 4 = 20

10 ร— 3 = 30

๐Ÿ”น Variable Scope

Variables inside functions have local scope and can't be accessed outside:

<?php
$globalVar = "I'm global";

function testScope() {
    $localVar = "I'm local";
    echo $localVar . "<br>";
    
    // Access global variable using 'global' keyword
    global $globalVar;
    echo $globalVar;
}

testScope();
// echo $localVar; // This would cause an error
?>

Output:

I'm local

I'm global

๐Ÿ”น Common Built-in Functions

PHP provides many useful built-in functions:

<?php
// String functions
echo strlen("Hello"); // Length: 5
echo "<br>";
echo strtoupper("hello"); // HELLO
echo "<br>";
echo str_replace("World", "PHP", "Hello World"); // Hello PHP

echo "<br><br>";

// Math functions
echo abs(-15); // 15
echo "<br>";
echo round(4.7); // 5
echo "<br>";
echo max(2, 8, 5, 1); // 8
?>

Output:

5

HELLO

Hello PHP


15

5

8

๐Ÿ”น Practical Example

Create a simple calculator using functions:

<?php
function calculate($num1, $num2, $operation) {
    switch($operation) {
        case 'add':
            return $num1 + $num2;
        case 'subtract':
            return $num1 - $num2;
        case 'multiply':
            return $num1 * $num2;
        case 'divide':
            return $num2 != 0 ? $num1 / $num2 : "Cannot divide by zero";
        default:
            return "Invalid operation";
    }
}

echo "10 + 5 = " . calculate(10, 5, 'add');
echo "<br>";
echo "10 - 5 = " . calculate(10, 5, 'subtract');
echo "<br>";
echo "10 ร— 5 = " . calculate(10, 5, 'multiply');
echo "<br>";
echo "10 รท 5 = " . calculate(10, 5, 'divide');
?>

Output:

10 + 5 = 15

10 - 5 = 5

10 ร— 5 = 50

10 รท 5 = 2

๐Ÿ’ก Function Best Practices:

  • Descriptive Names: Use clear names that describe what the function does
  • Single Purpose: Each function should do one thing well
  • Keep it Short: Functions should be concise and focused
  • Use Comments: Document complex functions with comments
  • Return Values: Return values instead of echoing when possible

๐Ÿง  Test Your Knowledge

What keyword is used to create a function in PHP?