A Beginner’s Guide to using Functions in PHP

Where necessary, you may need to have access to a VPS server so you can follow how to implement the steps in this article.  You can get a cheaper VPS Server from Contabo with 4vCPU cores, 8GM RAM, and 32TB Bandwidth for less than $5.50 per month. Get this deal here now

Table of Contents

Cloud VPS S

$5.50 Monthly
  • 4 vCPU Cores | 8GB RAM


$15.50 Monthly
  • 6 vCPU Cores | 16GB RAM


$17.50 Monthly
  • 8 vCPU Cores | 24GB RAM

Functions in PHP play a crucial role in organizing and streamlining code execution. They allow developers to encapsulate specific tasks or routines that can be easily called from other parts of the code. With over 1000 built-in functions and the ability to create custom functions, PHP empowers developers to enhance code modularity and readability. Let’s delve into the fundamentals of PHP functions.

Basic Syntax of a PHP Function

To create a function in PHP, you need to follow a specific syntax:

   function functionName($argument1, $argument2, ...) {
      // Code to be executed
  • functionName: Every function needs a name, serving as its identifier.
  • $argument1, $argument2, …: Optionally, a function can have one or more arguments, allowing it to receive input.
  • Code to be executed: This is the body of the function where specific procedures are defined.

Example: Basic Function

Let’s start with a simple function that prints a predefined message:

   function greetUser() {
      echo "Hello Chloe!";

   // Calling the function

In this case, calling greetUser() would result in the output:

Hello Chloe!

Example: Function with Arguments

Functions can also take arguments to make them more versatile. Here’s an example:

   function greetWithName($name) {
      echo "Hello $name!";

   // Calling the function with an argument

The output of this function call would be:

Hello John!

Example: Function with Multiple Arguments

It’s possible to have more than one argument in a function. Let’s see how:

   function addNumbers($num1, $num2) {
      echo "The sum is: " . ($num1 + $num2);

   // Calling the function with multiple arguments
   addNumbers(3, 7);

Executing addNumbers(3, 7) would result in the output:

The sum is: 10

Example: Function with Return Value

Functions can also return values. Consider the following example:

   function differenceOfNumbers($num1, $num2) {
      return $num1 - $num2;

   // Calling the function and displaying the result
   echo "The difference of the given numbers is: " . differenceOfNumbers(10, 5);

The output of this code snippet would be:

The difference of the given numbers is: 5

String Functions

PHP comes bundled with a rich set of built-in functions that cover a wide range of functionalities. These functions are ready to use, providing developers with powerful tools to perform various tasks without having to reinvent the wheel. In this section, we’ll explore some commonly used built-in PHP functions.


The strlen() function returns the length of a string.

   $str = "Hello, World!";
   echo strlen($str);  // Output: 13

strtolower() and strtoupper()

These functions convert a string to lowercase or uppercase, respectively.

   $str = "Hello, World!";
   echo strtolower($str);  // Output: hello, world!
   echo strtoupper($str);  // Output: HELLO, WORLD!

Array Functions

Array functions in PHP are a set of built-in functions specifically designed to manipulate arrays. These functions provide a variety of operations to add, remove, modify, and traverse array elements efficiently. Here are some commonly used array functions in PHP:


The count() function returns the number of elements in an array.

   $numbers = [1, 2, 3, 4, 5];
   echo count($numbers);  // Output: 5

array_push() and array_pop()

These functions add an element to the end of an array (array_push()) or remove the last element from an array (array_pop()).

   $fruits = ["apple", "banana"];

   // Adding an element
   array_push($fruits, "orange");
   print_r($fruits);  // Output: Array ( [0] => apple [1] => banana [2] => orange )

   // Removing the last element
   print_r($fruits);  // Output: Array ( [0] => apple [1] => banana )


Creates an array:

   $numbers = array(1, 2, 3, 4, 5);


Adds one or more elements to the end of an array.

   $fruits = ["apple", "banana"];
   array_push($fruits, "orange");
   print_r($fruits);  // Output: Array ( [0] => apple [1] => banana [2] => orange )


Removes the last element from an array.

   $fruits = ["apple", "banana", "orange"];
   print_r($fruits);  // Output: Array ( [0] => apple [1] => banana )


Removes the first element from an array.

   $fruits = ["apple", "banana", "orange"];
   print_r($fruits);  // Output: Array ( [0] => banana [1] => orange )


Adds one or more elements to the beginning of an array.

   $fruits = ["banana", "orange"];
   array_unshift($fruits, "apple");
   print_r($fruits);  // Output: Array ( [0] => apple [1] => banana [2] => orange )


Extracts a portion of an array.

   $fruits = ["apple", "banana", "orange", "grape"];
   $subset = array_slice($fruits, 1, 2);
   print_r($subset);  // Output: Array ( [0] => banana [1] => orange )


Merges one or more arrays into a new array.

   $fruits1 = ["apple", "banana"];
   $fruits2 = ["orange", "grape"];
   $combined = array_merge($fruits1, $fruits2);
   print_r($combined);  // Output: Array ( [0] => apple [1] => banana [2] => orange [3] => grape )


Reverses the order of elements in an array.

   $fruits = ["apple", "banana", "orange"];
   $reversed = array_reverse($fruits);
   print_r($reversed);  // Output: Array ( [0] => orange [1] => banana [2] => apple )


This checks if a specific value exists in an array.

$fruits = ["apple", "banana", "orange"];
echo in_array("banana", $fruits);  // Output: 1 (true)

Mathematical Functions

Mathematical functions in PHP are a set of built-in functions that provide various mathematical operations. These functions enable developers to perform calculations, handle numbers, and solve mathematical problems. Here are some commonly used mathematical functions in PHP:


The pow() function raises a number to the power of another.

   echo pow(2, 3);  // Output: 8


The sqrt() function calculates the square root of a number.

   echo sqrt(25);  // Output: 5


Raises a number to the power of another.

$base = 2;
$exponent = 3;
echo pow($base, $exponent);  // Output: 8


Rounds a floating-point number to the nearest integer.

$number = 4.6;
echo round($number);  // Output: 5


Rounds a floating-point number down to the nearest integer

$number = 4.9;
echo floor($number);  // Output: 4


Rounds a floating-point number up to the nearest integer.

   $number = 4.1;
   echo ceil($number);  // Output: 5


Generates a random integer.

   $randomNumber = rand(1, 10);
   echo $randomNumber;  // Output: Random integer between 1 and 10

min() and max()

Returns the minimum or maximum value from a list of arguments.

   $numbers = [3, 8, 2, 5];
   echo min($numbers);  // Output: 2
   echo max($numbers);  // Output: 8

sin(), cos(), tan()

Trigonometric functions that return the sine, cosine, and tangent of an angle, respectively.

   $angle = 45;  // Angle in degrees
   echo sin(deg2rad($angle));  // Output: 0.70710678118655 (sin of 45 degrees)


Returns the natural logarithm of a number.

$number = 2.71828;  // Euler's number
echo log($number);  // Output: 1

Date and Time Functions


The date() function formats a timestamp into a human-readable date.

   echo date("Y-m-d");  // Output: Current date in the format YYYY-MM-DD


The strtotime() function parses any English textual datetime description into a Unix timestamp.

   echo strtotime("next Monday");  // Output: Unix timestamp for the next Monday

These examples only scratch the surface of the numerous built-in functions PHP offers. Whether it’s manipulating strings, working with arrays, performing mathematical calculations, or handling date and time, PHP’s built-in functions provide a versatile toolkit for developers. You can always refer to the official PHP documentation for an exhaustive list of functions and their details.

Creating Custom Functions

Now, let’s further explore the creation of custom functions with additional examples to deepen your understanding.

Example: Function with Default Argument

PHP allows you to set default values for function arguments. This is useful when you want to provide a default if the caller doesn’t specify a value.

   function greetWithDefault($name = "Guest") {
      echo "Hello $name!";

   // Calling the function without an argument
   greetWithDefault();  // Output: Hello Guest

   // Calling the function with an argument
   greetWithDefault("Alice");  // Output: Hello Alice

Example: Function with Variable Scope

Understanding variable scope is crucial in PHP. Variables defined inside a function have local scope, and they are not accessible outside the function.

   $globalVar = "I'm global!";

   function localScopeExample() {
      $localVar = "I'm local!";
      echo $localVar;

   // Calling the function
   localScopeExample();  // Output: I'm local!

   // Trying to access the local variable outside the function
   echo $localVar;  // This would result in an error

Example: Recursive Function

PHP supports recursive functions, allowing a function to call itself. Here’s an example of a simple recursive function to calculate the factorial of a number.

   function factorial($n) {
      if ($n <= 1) {
         return 1;
      } else {
         return $n * factorial($n - 1);

   // Calling the recursive function
   echo "Factorial of 5 is: " . factorial(5);  // Output: 120

Understanding PHP functions is essential for any developer. As you progress in your PHP journey, you’ll encounter more complex scenarios and functions. Experiment with creating your functions, explore built-in functions, and always refer to the PHP documentation for additional insights.

Hire us to handle what you want

Hire us through our Fiverr Profile and leave all the complicated & technical stuff to us. Here are some of the things we can do for you:

  • Website migration, troubleshooting, and maintenance.
  • Server & application deployment, scaling, troubleshooting, and maintenance
  • Deployment of Kubernetes, Docker, Cloudron, Ant Media, Apache, Nginx,  OpenVPN, cPanel, WHMCS, WordPress, and more
  • Everything you need on AWS, IBM Cloud, GCP, Azure, Oracle Cloud, Alibaba Cloud, Linode, Contabo, DigitalOcean, Ionos, Vultr, GoDaddy, HostGator, Namecheap, DreamHost, and more.

We will design, configure, deploy, or troubleshoot anything you want. Starting from $10, we will get your job done in the shortest time possible. Your payment is safe with Fiverr as we will only be paid once your project is completed.