Learning PHP Part 3: Functions and More Conditional Statements

Rate article down Rate article up 0 subscribe to cyberstream photos rss feed
Download the Opera: a fast, efficient, feature-packed, secure, personalizable web browser. A strong point of PHP is functions. A function is a predefined procedure that can be executed at any time. You can call a function a couple of ways. PHP has hundreds of built-in functions. If you can't find a function that does what you want, you can create your own functions! Here's the syntax for creating a function:
function name([ args, ... ]) {
   //code to execute in the function
First we write the function keyword. Next is the function name. It follows the same naming rules as variables. Make the name concise, yet adequately descriptive of what the function does. Next is a set of opening and closing parentheses. You can leave these parentheses empty, or you can define any number of parameters for the function, which we'll look at later.

Calling Functions

When you create the function, it won't do anything. To execute it, you must call the function. To do this, you simply write the function name with the parentheses after it.
$name = 'Eli';


//strlen is a built-in PHP function that outputs the length of a string. In this case, it should output "3" because "Eli" is three characters long. 
Wait a minute. Nothing happened. What's going on?

Returning Values

This brings up an important part of functions. Most functions don't print out the value. They simply return it. That means that the function, if successfully executed, is holding a value. In this case, strlen($name) is holding the value, "3". You can do anything with this value. You can echo it out, assign it to a variable, operate on it, and more!
$name = 'Eli';

echo strlen($name); // "3"
echo strlen($name) * 2; // "6"

$name_length = strlen($name); // assigns the string length to $name_length

echo $name_length; // "3" 
You could create a function that directly prints out the value:
function myName() {
   echo 'Eli Mitchell';

myName(); // "Eli Mitchell" 
However, this is not acceptable in many instances. Suppose you wanted to assign "myName()" to a variable. That would not be possible without printing out the value. You can return a value by simply placing the return keyword before the data you wish to return. Returning will immediately stop the execution of a function and pass the returned value back to where the function was called. This is why values are usually returned at the end of a function. However, you do not have to place the return keyword at the end of the function. Consider this example.
function greet($name) {
   if ( strlen($name) < 3 ) return false; 

   return 'Hello, ' . $name;
This checks that there are at least 3 characters in the $name. If there are less than 3 characters in $name, then the function returns the boolean value false and aborts. Because of this, 'Hello ' . $name will never be returned. Why did we return false? False is the traditional value to return when a function fails. We will see later how we can use that to our advantage with conditional statements. On a side note, you may see I how did not use curly braces for the conditional statement. That's because curly braces are not required when there is only one statement to be executed after the conditional test. In this case, that statement is return false.


Notice how we passed the $name variable to the strlen() function. Let's look at how we can create functions with parameters.
function add($num1, $num2 = 0) {
   $result = $num1 + $num2;
   return $result;

echo add(4, 4); // "8"
echo add(4); // "4"
There's a lot of new stuff going on here. Let's start with examining the parameters. Each of the parameters is represented by a variable between the parentheses when you create the function. When you call the function, you substitute those variables for the actual values you want to assign to those variables. These variable names are completely arbitrary. However, as with the function name, make them as descriptive as possible.

Variable Range

The parameter variables ($num1 and $num2) are only accessible within the function. If you tried to echo $num1 (or $num2) outside the function, you'd get an error. Likewise, values outside the function are not available within the function, by default. However, you can access global variables two ways within a function.
$number = 12;

function add($num1) {
    return $num1 + $number; //error; undefined variable: $number

function subtract($num1) {
   global $number; 

   return $number - $num1;

function multiply($num1) {
   return $GLOBALS['number'] * $num1;
When you use the global keyword on a variable within a function, that global variable is available in the remainder of the function. However, you may only need to access the global variable a couple times. In this case, you can use $GLOBALS['global_variable_name'].

Optional Parameters

Notice how the second parameter of our add() function looked like it was being assigned a value of "0". This is an optional parameter. Basically this is what it means: "if the second parameter is not present when the function is called, assign $num2 a default value of 0." You can see this in action when we called the function the second time with only one parameter. Logically, optional parameters must be placed at the rightmost end of the argument list. This is why:
function test($arg1 = '', $arg2) { // optional param is first
   return $arg1 . ' ' . $arg2;

echo test('arg2'); //error; test() expecting 2 arguments - only 1 given.
PHP doesn't know that you wanted to set $arg1 to its default value and pass 'arg2' to $arg2. This function, stated correctly, should look like this:
function test($arg1, $arg2 = '') {
   return $arg1 . ' ' . $arg2;
As I said at the beginning of this post, PHP has hundreds of functions. If you see a PHP function somewhere that you want to look up, you can look it up in the PHP manual simply by entering the URL, http://www.php.net/function_name. The PHP manual is an indispensable reference tool. Here's a list of functions you may use commonly.

More Conditional Statements

I wanted to introduce you to functions before I delved deeper into conditional statements. Many times, you will want to test if a function was executed fully, or you may want to use functions to determine information about data (such as the strlen() function we've been using). Remember what the if () statement does? It tests the boolean truth of the given condition(s). If you forgot how to determine the boolean value of an object, check out the section, "Determining the Boolean Value of Objects", in Learning PHP Part 2. If you still can't figure out the boolean value of an object, simply cast it to the boolean type.
$object = 'foo';

echo (boolean) $object; 
//...or the boolean value for a function return value:
echo (boolean) isset($object); //"true", because $object is set 
You can easily check if a function was successful and dynamically run your web page based on the results:
$hour = date('G'); // hour in 24-hour format

if (!isset($hour) || !$hour) {
   echo 'Error: time unknown.';
} elseif ($hour < 9) {
   echo 'Good Morning!';
} elseif ($hour >= 9 && $hour < 17) {
   echo 'Good Afternoon.';
} else echo 'Good Evening.'; 
First, we begin by assigning $hour to the current hour (in 24-hour format). Then we move on to the if statement. Notice how we used the "!" (exclamation point) directly before the first conditional test. That operator negates the boolean value of that object (true becomes false, vice-versa). That operator is often referred to as "not". So what we basically said is this: "if it is true that the $hour variable is not set, OR (||) that $hour is not true, then echo an error message"; In what instances would $hour be false? If the [code]date()[/code] function was not successful, then the variable would be false. This example wasn't the best illustration of how to use the isset() function. Obviously, this variable will always have a value since we just assigned it. However, we'll use the isset() function a lot when we start processing forms from web pages.


You will find yourself using functions and conditional statements a lot when writing PHP applications. Coming soon, we'll learn about ways to manipulate strings and PHP's control structures. Actually, conditional statements are included in that category, so you've got a head start! Have any questions/thoughts? Post a comment, and I'd be happy to hear what you have to say.

Posted February 28, 2011 at 10:04PM by Eli Mitchell in PHP, programming with 0 responses

Post a comment!

Your website: (optional)

Your comment: