Getting Started with PHP Functions


Understanding PHP Functions

Functions are blocks of code designed to perform specific tasks. Functions allow you to reuse code and improve readability in your program.

1. Syntax of a PHP Function

In PHP, functions are defined using the function keyword, followed by the function name and parentheses:

function functionName() {
    // code to be executed;
}

2. Example of a Basic PHP Function

This example defines a simple function that prints a greeting:

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

Output:

Hello, welcome to PHP Functions!

3. Functions with Parameters

Parameters allow you to pass values to a function. This example demonstrates a function with parameters:

function addNumbers($num1, $num2) {
    return $num1 + $num2;
}

4. Example Usage of Function with Parameters

This example uses a function to add two numbers:

<?php
function addNumbers($num1, $num2) {
    return $num1 + $num2;
}
$result = addNumbers(5, 10);
echo "The sum is: $result";
?>

Output:

The sum is: 15

5. Returning Values from Functions

Functions can return values using the return keyword. The returned value can then be used in the code that called the function.

6. Example of a Function with Return Value

This example shows a function that returns the square of a number:

<?php
function square($number) {
    return $number * $number;
}
echo "The square of 4 is: " . square(4);
?>

Output:

The square of 4 is: 16

Using functions helps keep code organized, reusable, and modular. They play a crucial role in any PHP project.