What To Know About Functions In PHP

Posted by TotalDC

In the last article, we talked about various loops in PHP and how to use them. Now let’s look at PHP functions and everything you need to know about them then you are starting to program in PHP.

PHP Built-in Functions

First of all – a function is a self-contained block of code that performs a specific task.

As you may guess PHP has a large collection of built-in functions that you can call directly within your PHP code to perform a specific task, like var_dump(), gettype(), and lots more.

User-Defined Functions in PHP

But you are not just stuck with built-in functions. In PHP you can define your functions. It is a way to create reusable code that performs specific tasks and can be maintained separately from the main program. Let’s look at some of the advantages of using functions:

  • Functions reduce the repetition of code within a program — Function allows you to extract commonly used blocks of code into a single component. Now you can perform the same task by calling this function wherever you want within your script without having to copy and paste the same block of code again and again.
  • Functions make the code much easier to maintain — Since a function created once can be used many times, any changes made inside a function are automatically implemented at all places without touching several files.
  • Functions can be reused in other applications — Because a function is separated from the rest of the script, it’s easy to reuse the same function in other applications just by including the PHP file containing those functions.
  • Functions make it easier to eliminate the errors — When the program is subdivided into functions, if any error occurs you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier.

Now that that’s out of the way, we can look at how easily you can define your functions in PHP.

Creating And Invoking Functions In PHP

The basic syntax of creating a function looks like this:

function functionName(){
    // Your code goes here
}

You start your function with the word function, then write the name of your function followed by parentheses (), and then simply write your function’s code between curly brackets {}.

This is a simple example of a user-defined function:

<?php
// Defining function
function helloWorld(){
    print "Hello World!";
}
// Calling function
helloWorld();
?>

Functions With Parameters In PHP

Functions can have parameters that you specify when you create your function.

function yourFunction($parameterOne, $parameterTwo){
    // your code goes here
}

You can define as many parameters as you want. But keep in mind that the corresponding argument needs to be passed to the function when you call it.

The getSum() function in the following example takes two integer values as arguments, simply adds them together, and then displays the result in the browser.

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

The output of the above code will be:

Sum of the two numbers 5 and 10 is : 15

Functions With Default Values In PHP

You can define default values to your function’s parameters. Just insert the parameter name with the = sign and specify the default value of that parameter.

<?php
// Defining function
function customFont($font, $size=15){
    print "<p style=\"font-family: $font; font-size: {$size}px;\">Hello, world!</p>";
}
 
// Calling function
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
?>

In this example third call to customFont() includes the second argument. This forces PHP to use the default value for the $size parameter if no other value is given in your code.

Returning Values In PHP

A function can return value to the script that called the function using the return statement. You can return any type of value, including arrays and objects.

<?php
// Defining function
function getSum($num1, $num2){
    $total = $num1 + $num2;
    return $total;
}
 
// Printing returned value
print getSum(5, 10); // Result: 15
?>

Since a function can contain only one return statement, you have to use arrays to return multiple values.

<?php
// Defining function
function divideNumbers($dividend, $divisor){
    $result= $numOne / $numTwo;
    $array = array($numOne, $numTwo, $result);
    return $array;
}
 
// Assign variables as if they were an array
list($numOne, $numTwo, $result) = divideNumbers(10, 5);
print $numOne;  // Result: 10
print $numTwo;   // Result: 5
print $result;  // Result: 2
?>

Variable Scope In PHP

Although you can declare the variables anywhere in your PHP code, the location of the declaration determines the extent of a variable’s visibility within the PHP program (where the variable can be accessed). This is known as variable scope.

Variables declared within a {} of a function are local and they can’t be viewed or changed from outside of that function.

<?php
$greet = "Hello World!";
 
// Defining function
function greetUser(){
    print $greet;
}
 
greetUser();  // Generate undefined variable error
 
print $greet; // Result: Hello World!
?>

Global Variable In PHP

If you are in a situation where you need to import a variable from the main program into a function or vice versa you can use the global keyword before the variables inside the function. This keyword transforms your simple variable into a global variable, making it visible or accessible outside of the function.

<?php
$greet = "Hello World!";
 
// Defining function
function greetUser(){
    global $greet;
    print $greet;
}
 
greetUser(); // Result: Hello World!
print $greet; // Result: Hello World!
 
// Assign a new value to variable
$greet = "Goodbye";
 
greetUser(); // Result: Goodbye
print $greet; // Result: Goodbye
?>