PHP Functions

PHP Built-in Functions

A function in PHP is a self-contained block of code designed to perform a specific task.

PHP provides a wide array of built-in functions, such as gettype(), print_r(), var_dump(), and more, which can be directly used in your PHP scripts to accomplish various tasks.

For a comprehensive list of useful PHP built-in functions, please refer to the PHP reference section.

PHP User-Defined Functions

In addition to built-in functions, PHP allows developers to define their own functions. These user-defined functions enable the creation of reusable code blocks that perform specific tasks and can be maintained separately from the main program.

Here are some advantages of using functions:

  • Functions reduce code repetition — By encapsulating commonly used code into functions, you can perform tasks throughout your script without duplicating code.
  • Functions enhance code maintainability — Changes made within a function are automatically applied wherever the function is called, streamlining updates and reducing errors.
  • Functions facilitate error handling — When errors occur, functions isolate where the issue originates, simplifying debugging and troubleshooting.
  • Functions promote code reuse — Since functions are modular, they can be easily reused across different applications by including the PHP file containing those functions.

The next section demonstrates how to create and use your own functions in PHP.


Creating and Calling Functions

The basic syntax for defining a custom function is as follows:

function functionName(){
    // Code to be executed
}

To define a function, use the keyword function, followed by the function name and parentheses (). The function's code is then placed within curly braces {}.

Here's a simple example of a user-defined function that displays today's date:

<?php
// Defining function
function whatIsToday(){
echo "Today is " . date('l', mktime());
}
// Calling function
whatIsToday();
?>

 

Note: Function names in PHP must begin with a letter or underscore, followed optionally by more letters, numbers, or underscores. Function names are case-insensitive.


Functions with Parameters

You can define parameters in your function to accept input values when the function is called. Parameters act as placeholder variables within the function, replaced by actual values (known as arguments) provided during invocation.

function myFunc($oneParameter, $anotherParameter){
    // Code to be executed
}

You can specify multiple parameters. Each parameter requires a corresponding argument when calling the function.

The getSum() function in the following example accepts two integer arguments, adds them together, and outputs the result:

<?php
// Defining function
function getSum($num1, $num2){
$sum = $num1 + $num2;
echo "Sum of the two numbers $num1 and $num2 is : $sum";
}

// Calling function
getSum(10, 20);
?>

The result of executing the above code will be:

Sum of the two numbers 10 and 20 is : 30

Tip: An argument refers to a value passed to a function, while a parameter is the variable inside the function that receives this value. In everyday usage, these terms are often used interchangeably.


Using Functions with Optional Parameters and Default Values

Functions can include optional parameters by specifying a default value using the equals sign (=). This allows you to define parameters that are not required to be explicitly passed.

<?php
// Defining function
function customFont($font, $size=1.5){
echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>";
}

// Calling function
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
?>

Notice how the third invocation of customFont() omits the second argument. In such cases, PHP will utilize the default value assigned to the $size parameter, which is 1.5.


How Functions Return Values

Functions can send a value back to the part of the script that called them using the return statement. This value can be of any type, such as arrays or objects.

<?php
// Defining function
function getSum($num1, $num2){
$total = $num1 + $num2;
return $total;
}

// Printing returned value
echo getSum(5, 10); // Outputs: 15
?>

A function is unable to return multiple values directly. Instead, you can achieve similar functionality by returning an array, as illustrated in the following example.

<?php
// Defining function
function divideNumbers($dividend, $divisor){
$quotient = $dividend / $divisor;
$array = array($dividend, $divisor, $quotient);
return $array;
}

// Assign variables as if they were an array
list($dividend, $divisor, $quotient) = divideNumbers(10, 2);
echo $dividend;  // Outputs: 10
echo $divisor;   // Outputs: 2
echo $quotient;  // Outputs: 5
?>

How Arguments are Passed to Functions in PHP

PHP allows arguments to be passed to a function either by value or by reference. By default, arguments are passed by value, meaning changes to the argument within the function do not affect its value outside the function. However, to enable a function to modify its arguments directly, they must be passed by reference.

To pass an argument by reference, prefix the argument name with an ampersand (&) in the function definition, as demonstrated in the example below:

<?php
/* Defining a function that multiply a number
by itself and return the new value */
function selfMultiply(&$number){
$number *= $number;
return $number;
}

$mynum = 5;
echo $mynum; // Outputs: 5

selfMultiply($mynum);
echo $mynum; // Outputs: 25
?>

Understanding Variable Scope in PHP

In PHP, variables can be declared anywhere within a script. However, where a variable is declared determines where it can be accessed or used throughout the program. This concept is known as variable scope.

By default, variables declared within a function are local and cannot be accessed or modified from outside of that function, as illustrated in the example below:

<?php
// Defining function
function test(){
$greet = "Hello World!";
echo $greet;
}

test(); // Outputs: Hello World!

echo $greet; // Generate undefined variable error
?>

Likewise, attempting to access or import an external variable within the function will result in an error stating that the variable is undefined, as illustrated in this example:

<?php
$greet = "Hello World!";

// Defining function
function test(){
echo $greet;
}

test();  // Generate undefined variable error

echo $greet; // Outputs: Hello World!
?>

As demonstrated in the examples above, a variable declared inside a function cannot be accessed from outside, and similarly, a variable declared outside a function cannot be accessed from within it. This separation helps prevent variables within a function from being influenced by variables in the main program.

Tip: It is possible to reuse the same name for a variable in different functions, since local variables are only recognized by the function in which they are declared.

The global Keyword

There might arise a scenario where you want to bring a variable from the main program into a function, or vice versa. In these situations, you can employ the global keyword before the variable within the function. This keyword transforms the variable into a global one, enabling its visibility and accessibility both inside and outside the function, as demonstrated in the example below:

<?php
$greet = "Hello World!";

// Defining function
function test(){
global $greet;
echo $greet;
}

test(); // Outpus: Hello World!
echo $greet; // Outpus: Hello World!

// Assign a new value to variable
$greet = "Goodbye";

test(); // Outputs: Goodbye
echo $greet; // Outputs: Goodbye
?>

You will explore further about visibility and access control in the PHP classes and objects chapter.


Creating Recursive Functions

A recursive function is a function that calls itself repeatedly until a specific condition is met. Recursive functions are commonly employed for solving intricate mathematical computations or handling deeply nested structures, such as printing all elements of a deeply nested array.

The subsequent example illustrates the functioning of a recursive function.

<?php
// Defining recursive function
function printValues($arr) {
global $count;
global $items;

// Check input is an array
if(!is_array($arr)){
die("ERROR: Input is not an array");
}

/*
Loop through array, if value is itself an array recursively call the
function else add the value found to the output items array,
and increment counter by 1 for each value found
*/
foreach($arr as $a){
if(is_array($a)){
printValues($a);
} else{
$items[] = $a;
$count++;
}
}

// Return total count and values found in array
return array('total' => $count, 'values' => $items);
}

// Define nested array
$species = array(
"birds" => array(
"Eagle",
"Parrot",
"Swan"
),
"mammals" => array(
"Human",
"cat" => array(
"Lion",
"Tiger",
"Jaguar"
),
"Elephant",
"Monkey"
),
"reptiles" => array(
"snake" => array(
"Cobra" => array(
"King Cobra",
"Egyptian cobra"
),
"Viper",
"Anaconda"
),
"Crocodile",
"Dinosaur" => array(
"T-rex",
"Alamosaurus"
)
)
);

// Count and print values in nested array
$result = printValues($species);
echo $result['total'] . ' value(s) found: ';
echo implode(', ', $result['values']);
?>

Note: Exercise caution when developing recursive functions, as improper code may lead to an infinite loop of function calls.