User-Defined Functions

In addition to PHP's built-in functions, you can create your own functions. Remember that if you want to use variables that exist outside of the function, then you must declare them as global variables or assign them as arguments to the function itself.

function check_age($age) { 
    if ($age > 21) {
        return 1;
    } else {
        return 0;
    }
}
//usage:
if(check_age($age)) {
    echo "You may enter!";
} else {
    echo "Access Not Allowed!";
    exit;
}

The function would be called from within your script at the appropriate time, using the following syntax:

$age = 10; 
check_age($age);
// prints "Access Not Allowed!" to the screen

Get Advanced PHP for Web Professionals now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.