PHP Functions

by Vincy. Last modified on July 1st, 2022.

Functions are used to group the logical component of a program. The code performing a particular task will be put into a function and called wherever it is required.

Using functions we can write a clean program with the structured blocks of code. It will be easy to understand the program at the time of maintenance and for future reference.

Functions are used to separate a larger program and make room by grouping functionalities. It helps to reuse the functional blocks again and prevents duplication of the code.

Functions can either be user-defined or pre-defined. They accept params and return the result after processing the data. The function parameters are coming under the local scope of the function and can be visible within the functional block only.

In this article, I have added an example code for creating and using PHP functions.

Caution: 

Functions should not start with __ (double underscore) character, since, the PHP magic functions are starts with this character for example __clone().

A Function with a return type must return any value. Otherwise, an error will occur on execution.

Creating a Simple PHP function

The code shows how to define and invoke the PHP function. I created a function calculateTotal() to compute the total of ‘n’ numbers. We have to pass ‘n’ as the argument while invoking the function.

This function applies the formula for counting the total of the ‘n’ number and returns the result.

<?php
$numbersCount = 5;
$total = calculateTotal($numbersCount);
echo $total;

function calculateTotal($n)
{
    $result = ($n * ($n + 1)) / 2;
    return $result;
}
?>

PHP Functions with Default Params

PHP functions with default params will use them when we call this function without passing the parameters. Without these default values, it will cause an error when we call the function without passing arguments explicitly.

The following code shows an example of the PHP function with default parameters. I defined a function to return the weekday name with the use of PHP date functions. It accepts a date value as its argument. If no argument is sent, then it will take the default param value.

<?php
// passing arguments
$result1 = getWeekdayName('2013-04-20'); // returns Saturday
echo $result1;

// without params
$result2 = getWeekdayName(); // returns Tuesday
echo $result2;

function getWeekdayName($date = '2012-03-20')
{
    $timestamp = strtotime($date);
    $weekdayName = date('l', $timestamp);
    return $weekdayName;
}
?>
Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page