Lesson 26 of 50 – PHP Functions
52%

PHP Functions

A function is a reusable block of code that performs a specific task. Functions help us organize code, reduce repetition, and make programs easier to maintain.

1. What Is a Function?

PHP functions are defined using the function keyword. The code inside a function runs when the function is called.

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

greet();
?>
Output:
Hello, Welcome to PHP!

In this example, greet() is the function name. Calling greet(); executes the statements inside the function.

2. Creating and Calling a Function

A function can contain multiple statements. You can call it whenever you need to perform the same task.

<?php
function displayMessage() {
    echo "Welcome to Soopro Pathshala!<br>";
    echo "Learn PHP step by step.<br>";
}

displayMessage();
displayMessage();
?>
Output:
Welcome to Soopro Pathshala!
Learn PHP step by step.
Welcome to Soopro Pathshala!
Learn PHP step by step.

The function is defined once but called twice. Each call executes its statements again.

3. Functions with Parameters

Parameters allow a function to receive data when it is called.

<?php
function greetStudent($name) {
    echo "Hello, " . $name . "!<br>";
}

greetStudent("Rahul");
greetStudent("Amit");
greetStudent("Priya");
?>
Output:
Hello, Rahul!
Hello, Amit!
Hello, Priya!

Here, $name is a parameter. The values supplied in the function calls are arguments.

Parameters make functions reusable with different input values.

4. Functions with Multiple Parameters

A function can accept multiple parameters separated by commas.

<?php
function addNumbers($a, $b) {
    echo "Sum: " . ($a + $b);
}

addNumbers(10, 20);
?>
Output:
Sum: 30

Another example:

<?php
function studentDetails($name, $course, $city) {
    echo "Name: " . $name . "<br>";
    echo "Course: " . $course . "<br>";
    echo "City: " . $city . "<br>";
}

studentDetails("Rahul", "PHP", "Patna");
?>
Output:
Name: Rahul
Course: PHP
City: Patna

The arguments are passed in the same order as the parameters in the function definition.

5. Returning a Value from a Function

The return statement sends a value back to the code that called the function.

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

$result = add(15, 25);

echo "Result: " . $result;
?>
Output:
Result: 40

The returned value can be stored in a variable, displayed, or used in another calculation.

Example: Calculate a square

<?php
function square($number) {
    return $number * $number;
}

echo square(5);
?>
Output:
25

A return statement also ends the current function execution.

6. Functions with Default Parameters

A parameter can have a default value. PHP uses that value when the caller does not provide an argument for that parameter.

<?php
function greet($name = "Student") {
    echo "Welcome, " . $name . "!<br>";
}

greet();
greet("Rahul");
greet("Priya");
?>
Output:
Welcome, Student!
Welcome, Rahul!
Welcome, Priya!

Another example:

<?php
function calculateTotal($price, $quantity = 1) {
    return $price * $quantity;
}

echo calculateTotal(500);
echo "<br>";
echo calculateTotal(500, 3);
?>
Output:
500
1500

Default values are useful when a function argument is optional. Required parameters should generally be declared before optional parameters.

7. Type Declarations in Functions

PHP supports parameter and return type declarations. They help communicate the expected data types and detect certain type errors.

<?php
function addNumbers(int $a, int $b): int {
    return $a + $b;
}

echo addNumbers(10, 20);
?>
Output:
30

The parameters are declared as integers, and : int declares the return type.

Example with a string return type:

<?php
function getCourse(): string {
    return "PHP Programming";
}

echo getCourse();
?>
Output:
PHP Programming

PHP's type behavior depends partly on whether strict typing is enabled. Type declarations do not replace input validation when processing untrusted data.

8. Anonymous Functions

An anonymous function is a function without a declared name. It can be stored in a variable and called through that variable.

<?php
$greet = function ($name) {
    return "Hello, " . $name;
};

echo $greet("Rahul");
?>
Output:
Hello, Rahul

Anonymous functions are useful for callbacks and operations that need a function value.

Example using array_map():

<?php
$numbers = [1, 2, 3, 4, 5];

$squares = array_map(function ($number) {
    return $number * $number;
}, $numbers);

print_r($squares);
?>
Output:
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
)
9. Practical Example: Student Result Calculator

Functions can organize a program into reusable tasks. In this example, one function calculates the total marks and another calculates the average.

<?php
function calculateTotal($marks) {
    return array_sum($marks);
}

function calculateAverage($marks) {
    $count = count($marks);

    if ($count == 0) {
        return 0;
    }

    return calculateTotal($marks) / $count;
}

$studentName = "Rahul";
$marks = [80, 85, 90];

$total = calculateTotal($marks);
$average = calculateAverage($marks);

echo "Student: " . $studentName . "<br>";
echo "Total Marks: " . $total . "<br>";
echo "Average Marks: " . number_format($average, 2);
?>
Output:
Student: Rahul
Total Marks: 255
Average Marks: 85.00

This example demonstrates how functions can reuse logic, accept arguments, return results, and work together in a single program.

Practice Assignments
  1. Create a function that displays "Hello PHP".
  2. Create a function that accepts a name and displays a welcome message.
  3. Create a function that accepts two numbers and returns their sum.
  4. Create a function that calculates the square of a number.
  5. Create a function that calculates the area of a rectangle.
  6. Create a function with a default parameter for a student's course.
  7. Create a function that accepts three subject marks and returns the total.
  8. Create a function that returns the largest of two numbers.
  9. Create a function that calculates the average of an array of marks.

🧠 Quick Quiz

1. Which keyword is used to define a PHP function?




2. Which statement sends a value back from a function?




3. What is a default parameter value used for?