PHP Functions

This video was created by Dani Krossing

A function is a block of code set with an identifier, that can to be executed at some point in the future. PHP has many predefined functions, like is_array(), that allow us to perform a specific task, whenever we need for as many times as we need. That is advantage of using functions. It creates reusable code.

Calling a function

A function will not execute it's code until it is called. To call a function, write the function's name followed by a set of parentheses.

<?php phpinfo();

NOTE

Calling a function that has not been defined will result in an error.

Internal Functions

Internal Functionsopen in new window, as known as built-in functions, are function that come standard with PHP. PHP has hundreds of the internal functions, including some for variablesopen in new window, stringsopen in new window, arraysopen in new window, and mathopen in new window.

The following are some examples of using some internal functions.

isset

The issetopen in new window function is used to determine if a variable is declared and has a value other than NULL.

<?php 
$name = 'John'; 

echo isset($name); // true 
echo isset($fname); // false

implode

The implodeopen in new window function will join array elements into a string.

<?php 
$colors = ['red', 'blue', 'green'];

echo implode(",", $colors); // red,blue,green

in_array

The in_arrayopen in new window function checks if a specified value exists in an array.

<?php 
$colors = ['red', 'blue', 'green'];

echo in_array('red', $colors); // true
echo in_array('black', $colors); // false

rand

The randopen in new window function generates a random integer. An optional minimum and maximum number can be added to limit the pool of numbers.

<?php 
  // getting a random integer between 1 and 10 (inclusive)
  echo rand(1, 10); // possible response: 5

User-Defined Function

A user-defined functionopen in new window is a custom function that we create. A function is defined using the function keyword, an identifier or name, a set of parentheses, and a set of curly braces. The block of code to be executed goes inside the curly braces.

<?php
  function say_hello() {
    echo "Hello World!";
  }
?>

Arguments

Function argumentsopen in new window are data that is passed to a function through comma-separated list.

<?php 
  function say_hello_to($word) {
    echo "Hello {$word}!";
  }

  $name = "John Doe";
  say_hello_to($name); // Hello John Doe!
?>

Functions can be defined with more than one parameter, and therefore can accept more than one argument. When working with more than one parameter, the same number of arguments must be given, in the same order.

<?php
  function better_hello($greeting, $target, $punct) {
    echo "{$greeting} {$target}{$punct}<br>";
  }

  $name = "John Doe";
  better_hello("Greetings", $name, "!!!"); // Greetings John Doe!!! 
?>

NOTE

While the terms parameter and argument are often used interchangeably, they technically have different meanings. A parameter is a variable in the declaration of a function. An argument is the actual value of the variable that is passed to the function when it is called.

Default Arguments

Another feature of function argumentsopen in new window is providing a default value. Default function arguments allow for values to be predefined. When the value of an argument remains the same most of time, providing a predefined value can be beneficial and time-saving.

Default values are provided when the function is defined, and the syntax is similar to setting a value to a variable.

<?php 
  function paint($room = "office", $color = "red") {
    return "The color of the {$room} is {$color}.<br>"; 
  }
?>

When calling a function with default arguments, values can be omitted. But values still need to be provided in the correct order.

NOTE

The default value will only be used if nothing is passed as the argument. Therefore it is necessary that default arguments be placed at the end of the parameter list.

<?php 
  function paint($room = "office", $color = "red") {
    return "The color of the {$room} is {$color}.<br>"; 
  }

  // calling function using defaults
  echo paint(); // The color of the office is red.

  // calling function with provided values
  echo paint("bedroom", "blue"); // The color of the bedroom is blue.

  // calling function with null value
  echo paint("bedroom", null); // The color of the bedroom is .

  // calling function with only room
  echo paint("bedroom"); // The color of the bedroom is red.

  // calling function with only color
  echo paint("blue"); // The color of the blue is red.
?>

Returning Values

Returning valuesopen in new window from a function is a common and preferred practice. Values can be returned using a return statement.

The returnopen in new window statement immediately ends execution of the current function and returns its argument as the value of the function call.

NOTE

Best practice states that all customs should have a return statement. It is also a good idea, not use an echo statement inside a function.

<?php
  function add ($a, $b) {
    $sum = $a + $b;
    return $sum;
  }

  $result1 = add(3, 4);
  $result2 = add(5, $result1);
  echo $result2; // 12
?>

Variable Scope

Variable scopeopen in new window refers to the context in which a variable was defined where it is visible.

PHP has two types of scope, global scope and local scope. Variables defined inside a function are in local scope and are only accessible inside the function. Variables defined outside of a function is in global scope and are accessible everywhere except inside of a function.

<?php
  $a = 1; // global scope

  function test() {
    return $a; // local scope
  }

  var_dump(test()); // NULL
?>

If a global variable needs to be used in the a function, the variable must be defined inside the function using the global keyword. This ensure access to the global variable instead of the local one.

<?php
  $a = 1; // global scope

  function test() {
    global $a; // global scope

    return $a; // global scope
  }

  var_dump(test()); // int(1)
?>

NOTE

Use the global keyword and global variables with caution. It is often better to use parameters than to rely on global variables.