PHP Functions


A function is a self-contained code block that accomplishes a particular purpose.

Internal or built-in functions in PHP, such as gettype(), print_r(), var_dump(), and others, can be called directly from inside your PHP scripts to perform a particular task.


The following is the basic syntax for writing a custom function:


  function functionName(){
  // Your codes here
}



A user-defined function's declaration begins with the word function, then the name of the function you want to construct, followed by parentheses (), and finally the code for your function between curly brackets.

This is a basic user-defined feature for displaying the current date:


<?php
  // Defining function
  function whatIsToday(){
   echo "Today is " . date('l', mktime());
  }
  // Calling function
  whatIsToday();
?>



Functions with Parameters

When you define your function to accept input values at run time, you can specify parameters. The parameters act as placeholder variables within a function, with the values (known as argument) given to the function at the time of invocation replacing them at run time.


 function myFunc($oneParameter, $anotherParameter){
  // Your codes here
}



You are free to set as many parameters as you like. When the function is called, however, a corresponding argument must be passed to it for each parameter you define.

In the example below, the function getSum() takes two integer values as arguments, adds them together and shows the result in the browser.


<?php
  //  function
  function getSum($num1, $num2){
    $sum = $num1 + $num2;
    echo "The total Sum of the two numbers $num1 and $num2 is : $sum";
    }

  // Calling the function
  getSum(10, 20);
?>



Output


The total sum of two numbers 10 and 20 is : 30



Optional Parameters and Default Values in Functions

You can also construct functions with optional parameters by inserting the parameter name, an equal (=) symbol, and a default value, as shown here.


<?php
  //  function
  function customFont($font, $size=1.5){
  echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>";
  }

  // Calling function
  customFont("Arial", 2);
  customFont("Times", 3);
  customFont("Courier");
?>



The third call to customFont(), as you can see, does not contain the second statement. This allows the PHP engine to use the $size parameter's default value of 1.5.


Using a Function to Return Values

Using the return statement, a function will return a value to the script that called it. Every sort of value, including arrays and objects, can be used.


<?php
  //  function
  function getSum($num1, $num2){
    $total = $num1 + $num2;
    return $total;
  }

  // Printing
  // returned value
  echo getSum(5, 10); // Outputs: 15
?>



A function can't return more than one value. Returning an array, on the other hand, may produce similar results, as seen in the following example.


<?php
  // Defining function
  function divideNumbers($dividend, $divisor){
    $quotient = $dividend / $divisor;
    $array = array($dividend, $divisor, $quotient);
    return $array;
    }

  // Assign variables
  // as if they
  // were an array
  list($dividend, $divisor, $quotient) = divideNumbers(10, 2);
  echo $dividend;  // Outputs: 10
  echo $divisor;   // Outputs: 2
  echo $quotient;  // Outputs: 5
?>



Using a Reference to Transfer Arguments to a Function

You can transfer arguments to a function in PHP in two ways: by value and by comparison. By default, function arguments are transferred by value, which means that if the value of the argument changes within the function, it has no effect outside of it. However, a function's arguments must be transferred by reference in order for them to be modified.


As seen in the example below, passing an argument by reference is accomplished by appending an ampersand (&) to the argument name in the function definition:


<?php
  /* Defining a function that multiply a number
  by itself and return the new value */
  function selfMultiply(&$number){
  $number *= $number;
  return $number;
  }

  $mynum = 5;
  echo $mynum; // Outputs: 5

  selfMultiply($mynum);
  echo $mynum; // Outputs: 25
?>



global keyword

It's possible that you'll need to import a variable from the main program into a function, or the other way around. You may use the global keyword before the variables within a function in such cases. As seen in the example below, this keyword transforms the variable into a global variable, making it available or accessible both within and outside the function:


<?php
  $greet = "Hello World!";

  // Defining function
  function test(){
  global $greet;
  echo $greet;
  }

  test(); // Outpus: Hello World!
  echo $greet; // Outpus: Hello World!

  // Assign a
  // new value
  // to variable
  $greet = "Goodbye";

  test(); // Outputs: Goodbye
  echo $greet; // Outputs: Goodbye
?>