PHP Lesson 13 – Functions

Last updated on January 8th, 2024

Why are functions important?

Functions are a fundamental concept in PHP programming and many other programming languages. They are blocks of code that perform a specific task or a set of tasks, i.e. functions are something like small programs inside your program.

Functions are designed to be reusable, which means you can call them multiple times within your program without having to rewrite the same code. This makes your code more organized, efficient, and easier to maintain.

What’s in a function?

Functions differ from variables in that they do not contain the dollar sign or any other character in front of the name. All functions necessarily contain parentheses after their name, in which one or several parameters may be placed, or there may not be any parameters. Therefore, the usual form of functions is: function(). Once created, unlike a variable, a function cannot be changed.

The syntax of function names obeys the same rules as the syntax of variable names, i.e. a function name may contain Latin letters, Arabic numerals, and an underscore, and may begin with a letter or an underscore, but not a number.

Unlike variables, however, function names are not case-insensitive. I.e. the names function(), Function() and FUNCTION() will be treated by PHP as the same function.

How to define and call a function?

Function Definition:
In PHP, you define a function using the function keyword, followed by the function name and a pair of parentheses. For example:

function sayHello() {
echo “Hello, World!”;
}

In this example, we’ve defined a function called sayHello. The executable code of the function is enclosed in big curly braces: {echo “Hello, World!”;}

Function Invocation (Calling):
To execute a function and perform the tasks it contains, you need to call it by its name followed by parentheses. For example:

sayHello();

When you call sayHello(), it will execute the code inside the function, which in this case, will print “Hello, World!” to the screen:

<?php

  function sayHello() {
    echo "Hello, World!";
  }

  sayHello();

?>

Function Parameters:
Functions can accept parameters (also known as arguments) to make them more versatile. Parameters allow you to pass data into the function. For example:

function greet($name) {
echo “Hello, $name!”;
}

You can then call this function with a specific name as an argument:

greet(“John”);

This will output “Hello, John!”:

<?php

  function greet($name) {
    echo "Hello, $name!";
  }

  greet("John");

?>

Return Values:
Functions can also return values. You use the return statement to specify the value that the function should return. For example:

function add($a, $b) {
return $a + $b;
}

When you call this function and assign its result to a variable, like this:

$result = add(5, 3);

The value of $result will be 8, which is the result of the addition:

<?php

function add($a, $b) {
    return $a + $b;
}

$result = add(5, 3);
echo $result;

?>

Scope:
Variables defined within a function are typically only accessible within that function’s scope, unless explicitly declared as global. This is known as “variable scope.”

Function Reusability:
One of the primary benefits of functions is their reusability. You can call a function from different parts of your program, avoiding code duplication. This makes your code easier to maintain and reduces the chances of errors.

What types of functions are there?

There are several types of functions. The main ones are:

Built-in Functions:
PHP comes with a rich set of built-in functions that perform various tasks, such as string manipulation, mathematical calculations, file handling, and more. These functions save you time and effort by providing pre-built solutions to common programming tasks.

Built-in Functions are like ready-made tools that PHP provides. You don’t have to create them; they’re already there for you to use. For example, there’s a built-in function to count how many characters are in a word or sentence. Some examples of built-in functions include strlen(), strpos(), date(), array_push(),  file_get_contents().

User-Defined Functions:
You can create your own custom functions in PHP to perform specific tasks or encapsulate a set of instructions. Imagine you have a favorite recipe. You can write down the steps in your recipe book. In PHP, you can create your own “recipes” for doing things. You give your recipe a name and write down the steps so you can use it again and again.

Creating (declaring) your own function has the following syntax:

function name_of_function ($parameter1, $parameter2, $parameter3…) {code in the “body” of the function}

I.e. the keyword function is written first, then you must write a randomly chosen function name. The parentheses that follow the function name may or may not have any number of parameters. Next, large parentheses enclose the executable code from the “body” of the function.

Once a function is created (defined), it can be called as many times as you want and at any place in the code you want. You can put as many parameters as you want in the parentheses, and you can have as much code as you want in the big brackets.

Examples of using functions

Examples of built-in functions:

strlen():

<?php
  $text = "This is a sample text.";
  $length = strlen($text);
  echo "The length of the text is $length characters.";
?>

strlen() calculates the length (number of characters) in a given string. Here, it counts the characters in the variable $text and outputs the result as part of a sentence. The result of the above code will be: “The length of the text is 22 characters.” because the spaces between the words are also counted.

rand():

<?php
  $randomNumber = rand(1, 10);
  echo "Random number between 1 and 10: $randomNumber";
?>

rand() generates a random number between the specified range. In this case, it generates a random number between 1 and 10 and displays it.

date():

<?php
  echo "Today is " . date("Y-m-d");
?>

date() returns the current date and time. Here, it formats the date as “Year-Month-Day” and displays it as part of a sentence.

If you want to display a date in the format Day.Month.Year, you should use the following code:

<?php
  echo "Today is " . date("d.m.Y");
?>

phpinfo():
There is a very useful built-in function in PHP called phpinfo(). This function provides a comprehensive and detailed report of the current PHP configuration settings for a particular server. When you call phpinfo(), it automatically generates a webpage containing information about PHP compilation options, extensions, server information, environment variables, and more.

Just make a PHP page with the following code in it:

<?php
phpinfo();
?>

Save the page, for example as info.php, open the XAMPP admin panel, start the Apache server and place your page in the htdocs folder. Now open your browser and open the page info.php at address localhost/info.php to see the result.

Examples of user-defined functions:

Basic Function:

<?php
  // Define a simple function
  function sayHello() {
    echo "Hello, World!";
  }

  // Call the function
  sayHello();
?>

In this example, we define a function called sayHello(), which simply echoes “Hello, World!” when called. We then call the function using sayHello(), which displays the greeting.

Function with Parameters:

<?php
   // Define a function with parameters
   function addNumbers($num1, $num2) {
    $sum = $num1 + $num2;
    echo "The sum of $num1 and $num2 is $sum.";
}

// Call the function with arguments
addNumbers(5, 3);
?>

This function, addNumbers(), accepts two parameters ($num1 and $num2), adds them together, and then echoes the result. When we call the function with addNumbers(5, 3), it calculates and displays the sum which is 8.

Function with Return Value:

<?php
  // Define a function that returns a value
  function multiply($num1, $num2) {
    $result = $num1 * $num2;
    return $result;
}

// Call the function and store the result
$product = multiply(4, 6);
echo "The product is $product.";
?>

The multiply() function takes two parameters, multiplies them together, and returns the result. When we call the function with multiply(4, 6), it returns the product, which we then display (The product is 24.).

Function with Default Parameter:

<?php
     // Define a function with a default parameter
     function greet($name = "Guest") {
        echo "Hello, $name!";
    }

    // Call the function
    greet(); // Outputs "Hello, Guest!"
    greet("Alice"); // Outputs "Hello, Alice!"
?>

This function, greet(), has a default parameter $name set to “Guest.” If no argument is provided when calling the function, it uses the default value. When we call greet() without an argument, it greets “Guest,” and when we call it with an argument, it greets the specified name.

Example of using a PHP function together with HTML:

Let’s imagine that you have a web page where you need to display a list of some elements in several places. In that case, your code might look like this:

<!DOCTYPE html>
<html>
<head>
<title> Function Example </title>
</head>
<body>

<?php

  function mylist()
  {
  echo
  "<ul>
  <li> Item 1 </li>
  <li> Item 2 </li>
  <li> Item 3 </li>
  </ul>";
  }

  // Here we will show the list for the first time

  mylist();

?>

<p> Some text here. </p>

<?php

  // Here we can display it a second time

  mylist();

  ?>

</body>
</html>

In the code above, we created the mylist() function, which is parameterless, and then called it twice. This code will have the effect of displaying the list of items 1 to 3 twice. The page will look like this:

HTML list in PHP function

I.e. once the function has been created and the executable code has been set inside the braces, you can then call it one or more times simply by writing its name in the document code in the appropriate place.

Note that parentheses must be written after the function name, even though they may not contain any parameters, as in this case. The function call construct, like other constructs, ends with a semicolon.