Ugacomp

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

CLOUD VPS M

$15.50 Monthly
  • 6 vCPU Cores | 16GB RAM

CLOUD VPS L

$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:

<?php
   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:

<?php
   function greetUser() {
      echo "Hello Chloe!";
   }

   // Calling the function
   greetUser();
?>

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:

<?php
   function greetWithName($name) {
      echo "Hello $name!";
   }

   // Calling the function with an argument
   greetWithName("John");
?>

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:

<?php
   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:

<?php
   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.

strlen()

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

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

strtolower() and strtoupper()

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

<?php
   $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:

count()

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

<?php
   $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()).

<?php
   $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
   array_pop($fruits);
   print_r($fruits);  // Output: Array ( [0] => apple [1] => banana )
?>

array()

Creates an array:

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

array_push()

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 )

array_pop()

Removes the last element from an array.

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

array_shift()

Removes the first element from an array.

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

array_unshift()

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 )

array_slice()

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 )

array_merge()

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 )

array_reverse()

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 )

in_array()

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:

pow()

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

<?php
   echo pow(2, 3);  // Output: 8
?>

sqrt()

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

<?php
   echo sqrt(25);  // Output: 5
?>

pow()

Raises a number to the power of another.

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

round()

Rounds a floating-point number to the nearest integer.

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

floor()

Rounds a floating-point number down to the nearest integer

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

ceil()

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

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

rand()

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)

log()

Returns the natural logarithm of a number.

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

Date and Time Functions

date()

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

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

strtotime()

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

<?php
   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.

<?php
   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.

<?php
   $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.

<?php
   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.