Functions in PHP – A Simplified Guide

A “function” in programming terminology, is a group of statements that execute a particular task. There are various types of PHP functions that we’re going to cover in this tutorial.

But first, Let’s take an example to understand functions.

The abs( mixed $number ) is an inbuilt PHP function which returns the absolute value of a number. The “abs” is followed by an opening and closing braces.

In between, we have a parameter that we’re sending to the function; in this case, it’s -10.2.

If I echo $num, I should get the result of 10.2.
<?php
  $num = abs(-10.2);
  echo $num; // 10.2
?>
So, what happened? I sent a negative value to a function and got the equivalent absolute value. So, whats happening inside this cool black box called the “abs( mixed $number)“. You should already know by now, that the abs() function performed a certain task and that is to return the absolute value of an integer or a float number. How it solved that task, I cannot see. All I know is, calling abs() solves a particular problem. I could use the same function again and again.
<?php 
  echo abs(-4); // 4
  echo abs(-345); // 345
  echo abs(42); // 42
  echo abs(-8.765); // 8.765
?>
I have called abs() 4 times and it performed what it was meant to i.e return the absolute value. I could say the abs function is reusable. So, a function is a reusable block of code that performs a particular task. It can optionally return a value.

Why do we use functions?

As a programmer, functions are a life saver. In fact, without it, we would go insane writing repetitive statements. Functions help us greatly in
  • Modularizing code – We can break our code into functions, thus maintaining is easier.
  • Reusable code – You can see the example that I called abs 4 times, thus avoiding repetition.
  • Test small chunks of code – Oh yea. You don’t need to run an entire program to test whether your code works or not.

Defining a function

The general syntax for a defining a function in PHP is:
<?php
  function my_cool_function( arguments ) {
    // Statements
  }
?>
To define your function, you have to start with keyword function. Its followed by with letters or underscores and the opening and closing braces. We will discuss the arguments in the next section. Functions are case-sensitive. my_cool_function() is not the same as My_Cool_Function().

Returning values

Arguments or parameters are values that you pass to a function. Let’s create a function whose end result is to return the square of a number.
function calc_square( $val ) {
  $num = $val * $val;
  return abs( $num );
}

// call our function 
echo calc_square( 5 ); // 25
A rough analogy I’d give to explain parameters is your average calculator app. Imagine the keypad of my phone as a set of arguments. My app is the function, and the screen shows the return value. If I want to add 10 and 2 on the app, I will tap 10 as the first argument and 2 as the second argument. The return value of 12 is shown on the screen. I’m unaware of the logic that took place inside the app, but I’m damn sure that adding a couple of values to the app yields a result. Let’s create a function that adds two numbers, just for the lolz.
<?php

  function add( $num1, $num2 ) {
    return $num1 + $num2;
  }

  $val1 = 14;
  $val2 = 67;

  echo "<br>Val1 : " . $val1; // $val remains unchanged

  $val1 = add( $val1, $val2 ); // the add() returns a value
  echo "<br>Val1 : " . $val1; // $val1 overwritten by add()
  echo "<br>Val2 : " . $val2; // $val2 remains same

?>
But there is a caveat to functions. A function at a point of execution cannot return more than one value. If you see the examples earlier, you can see only one value being returned to the variable by the function. But what if we need more values from our function? Our answer to this problem is Arrays. Hooah! Arrays are the only data type to hold multiple values. We can pass an array as an argument as well as get an array as our return value. Let’s illustrate.
<?php

  function greet_user() {
    return array( "Soumil", "Roy" );
  }
  
  echo "<pre>";
  var_dump( greet_user() );
  echo "</pre>";

?>
You can see that the function has returned two values through an array. Let’s try another example. This time, I will send an array as a parameter and will get an array as my return value.
<?php

  function reverse_strings( $string ) {
      $string['first_name'] = ucfirst( strrev( $string['first_name'] ) ); 
      $string['last_name'] = ucfirst( strrev( $string['last_name'] ) );
      return $string; // return array
  }

  $bad_str = array(
    'first_name' => 'limuos', // incorrect string
    'last_name'  => 'yor'
  );

  $correct_string = reverse_strings( $bad_str );

  echo '<br>' . $correct_string['first_name']; // Soumil 
  echo '<br>' . $correct_string['last_name'];  // Roy

?>

Functions that return “nothing”

If your functions have no return statement, then it will return NULL by default. To test this, let’s work on an example.
<?php

  function func_with_no_return() {
    echo "Is this function returning something? LOL!";
  }

  $value = func_with_no_return(); // string is echoed though

  if ( is_null( $value ) ) { // inbuilt PHP func to check for NULL    
    echo "<br> Tough luck bro.. you got nuthin..!";
  }

?>
Now change that echo inside the function to return and check the result. You might have noticed that the function has no arguments. Yes. A function can have zero arguments. But when you’re programming in real life, you will use functions with arguments quite extensively.

Leave a Comment

Your email address will not be published. Required fields are marked *