PHP functions

Sometimes you use a piece of code over and over again. This is not optimal and this code should be extracted to its own function.

A function is a block of code with a given name and can be called (executed) by this name and optionally passed arguments to change the behaviour/output of the function.

We have already used a lot of PHP builtin functions. For example: print, isset, empty, array_pop, array_push, …

As mentioned we can define our own functions.

Syntax:

function <name> ( <arguments> ) {

    /* function code here */
}

Example: function without arguments

function greet() {
    echo "Hello!\n";
}

greet(); // Hello!
greet(); // Hello!

Example: function with arguments

function greet( $name ) {
    echo "Hello $name!\n";
}

greet( 'john' ); // Hello john!
greet( 'jane' ); // Hello jane!
greet(); // - ERROR -

If arguments are present in the function definition, these arguments must be passed when the function is invoked. Otherwise an error is thrown…

Arguments can however be defined with a default value, if the argument is not passed at invocation (or the argument value is NULL) the default value will be used instead.

Example: function with arguments

function greet( $name = 'anonymous' ) {
    echo "Hello $name!\n";
}

greet( 'john' ); // Hello john!
greet( 'jane' ); // Hello jane!
greet(); // Hello anonymous

Multiple arguments can be passed, separated by comma’s ,.

function greet_both( $first, $second = '' ) {

    echo "Hello $first";
    echo "Hello $second";
}

greet_both( 'john', 'jane' );
// Hello john
// Hello jane

greet_both('sam');
// Hello sam
// Hello

Return a value

The return keyword must be used to return a value from an array:

function fn() {
    return "Hello World";
}

$string = fn();

Whenever a return statement is encountered, the function will stop and return the specified value. Any code defined after the return statement will not be executed…

Example:

function fn() {

    if( true ) {

        return "was true";
    }

    echo "This will never execute because the function returned from the if statement";
}

Exercises

Exercise:

Create a function which accepts two arguments:

  • name
  • sentence

Output: <name> -> <sentence>

php chat.php 
john -> @jane: Hello
jane -> Hello john
john -> Nice weather...
jane -> Yep is is

Exercise:

Create a function which checks if a number is:

  • positive
  • even
  • and smaller then 100
if( check_number( $nr ) ) { echo "number ($nr) passed tests"; }
else { echo "number ($nr) failed tests"; }
php validate-number.php -5
number (-5) failed tests
php validate-number.php 7
number (7) failed tests
php validate-number.php 22
number (22) passed tests
php validate-number.php 111
number (111) failed tests

Exercise:

Create a barplot: 25%, 80%, 15%.

Abstract the bars away in a function.

print_bar('25%');
print_bar('80%');
print_bar('15%');
Example Solution:

Exercise:

Create a function for each arithmetic operator: +, -, x, /. The function should accept an array of values and apply the operations in sequence:

Example:

plus([1,2,3, 4]); // -> 10
subtract([10,5,1]); // -> ( 10 - 5 ) - 1
divide([100, 10, 5]) // -> ( 100 / 10) / 5
multiply([7,9,8,4]) // -> 7 * 9 * 8 * 4
  • Extra: accept two values: plus( 1, 2 ) or array: plus([1,2])
    Info: Use is_array to check if a variable is an array…
php arithmetic-operators.php 
10
4
2
2016

Exercise:

Create a function which can retrieve and validate data from an array (ex.: $_POST)

  • retrieve key from array
  • check if value is not empty (otherwise show error)
  • check if value is not longer than 50 characters (otherwise show error)
  • modify the function so a default value can be passed to the function, if the key is not found in the array, retrun this value.
php retrieve-key.php 
value1
default value
default value
value1
`keyx` not found in array

Exercise:

Extra: Create a function that can calculate the factorial of a number.

Try not to use loops but recursion…

php factorial.php 5
120