PHP Functions

Functions are user 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 future reference. Functions are used to separate a larger program and make rooms by grouping functionalities. It helps to reuse the functional blocks again and prevents duplication of the code. 

Functions can either be a 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 example code for creating and using PHP functions.

function-code

Caution: 

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

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

Creating 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 return 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 for the PHP function with default parameters. I defined a function to return the weekday name with the use of PHP date functions. It accepts 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;
}
?>

This PHP code tutorial was published on April 19, 2013.

↑ Back to Top