In our last two tutorials, we’ve learned how to create our own functions and some things we can do with them. Another important thing to learn about PHP functions is how to return values. If you send a value from your function to your script, you use the return statement. In every function you create, it’s a good habit to return a value, even if this value is only a boolean (true or false). When you return a value, it sends the value back to the script and ends the function.
The most common example of return values is to show a function using the sum of two numbers, so I’ll do that here:
<?php // This function will add two numbers and return the sum. function add_numbers($number1,$number2) { $total = $number1 + $number2; // add two numbers, assign to $total variable return $total; // here is our return value! } ?>
A return statement can only return one value. It is possible to return multiple values by using an array, but that is something we’ll cover another time.
So now that we’ve created our function, let’s use it!
<?php // This function will add two numbers and return the sum. function add_numbers($number1,$number2) { $total = $number1 + $number2; // add two numbers, assign to $total variable return $total; // here is our return value! } echo add_numbers(1,3); // This will output 4 because 1 + 3 = 4. ?>
And here’s another example with an If Statement:
<?php // This function will add two numbers and return the sum. function add_numbers($number1,$number2) { $total = $number1 + $number2; // add two numbers, assign to $total variable return $total; // here is our return value! } add_numbers(5,14); if ($total > 10) { echo "Our total is greater than 10."; // Tell user the sum is greater than 10. } else { echo "Our total is less than 10."; // Tell user the sum is less than 10. } ?>
Go back to Building PHP Scripts.
Let’s continue from where we left off in our Introduction to Functions tutorial. The basic structure of a PHP function is:
<?php function function_name(parameter1, parameter2, parameter3, etc.) { function code / statements } ?>
Functions have three sections: code, parameters, and return values.
The function code is where we write what our function will do. In our earlier example, we wrote three PHP echo statements.
In the parameters, you can pass a variable to your function. This is what gives your functions true flexibility and usefulness. Let’s make a quick example.
<?php function my_message($message) { echo "Listen everyone. I have an important thing to say. Are you ready?<br />"; echo "Okay then. Here it is: $message"; } ?>
So we have our function with its short two line phrases. Notice the $message variable has not been created but it is mentioned in the parameter. Let’s use it now.
<?php $message = "Hello world!"; // Now our $message variable exists. echo my_message($message); // Use the my_message function and pass it the $message data we just created. ?>
This is our output of the above code:
Listen everyone. I have an important thing to say. Are you ready? Okay then. Here it is: Hello world!
Here’s another use of this function:
<?php echo my_message("I like peanuts!"); // Will use the words inside the quotes. ?>
So now instead of using the $message variable, we’re passing a string. Let’s see our results:
Listen everyone. I have an important thing to say. Are you ready? Okay then. Here it is: I like peanuts!
Go back to Building PHP Scripts.
A function in PHP can save a lot of time by letting you quickly reuse a set of code. You will often have to use the same PHP code in many different spots. If it’s only one line of code, that’s no big deal. But what if it’s 10 lines, or 100 lines? You could copy and paste the code over and over, but that will start to look messy after a while. Creating your own functions enables you to store a bunch of code and refer to it easily.
PHP contains many pre-built functions. Back in the Testing Our Installation tutorial, we used the phpinfo() function. Besides the functions built into PHP, you could also install PHP extensions that give you even more functions to use. The official web site of PHP.net has a list of all their functions and sample usage. To quickly see a function, use the shortcut: www.php.net/Function_Name_Here
Not only do functions make your code cleaner to look at, but it makes your code easier to maintain. If you ever need to update your code in a function, you just update it in one spot. If you weren’t using functions and just copy and pasted your code everywhere, then you’d have to go into every file and make your changes. Like an old sandwich, this invites room for bugs and is a waste of your time. Functions are a key part of modular code which helps keep your scripts manageable.
Let’s build our own function. When naming a function, we end it with parentheses. Function names can contain numbers, but they can’t begin with a number. Let’s say we want to include the same message in many of our PHP files. Here’s one way to do it using functions:
<?php function my_message() { echo "Thank you very much for coming to my site!<br />"; echo "Please come back soon to see my latest updates.<br />"; echo "You can also email me with any questions.<br />"; } ?>
What we have here is a very basic function that consists of three echo statements. Let’s say I want to put it at the end of all my posts. Once I’ve created this function in my PHP file, I can refer to it later on by doing this:
<?php my_message(); ?>
And that’s it! Wherever I put my_message(), PHP will act as if I wrote the three lines of echo code we made above.
There’s much more to learn about PHP functions. Let’s continue to More With PHP Functions.
Go back to Building PHP Scripts.
Making mistakes is a natural part of life, especially if you’re a programmer. Often times you may spend more time fixing bugs than you will spend creating new features for your web application. The more complex of a feature, the more likely a bug will sneak in. Some bugs are practically harmless and no one ever finds them because they’re very subtle and don’t interfere with the application. Other bugs are extremely obvious and will cripple your web site until they are fixed. In this tutorial, you will learn common errors in PHP and how to fix them.
One of the most common PHP errors you’ll receive is a parsing error. It looks like this:
Parse error: parse error in localhost\feature.php on line 24
This happens when PHP doesn’t understand a section of your code. Fortunately, PHP tells you where in the code it got confused. In this example, something probably went wrong around line 24. The error message doesn’t always point directly to the line with the error, but it usually does.
Let’s take a look at the most common errors.
Incorrect Quotes
You have to be consistent with your use of quotes in PHP. For example:
<?php echo "Hello there.'; // starts with a double-quote, ends with a single-quote. ?>
This code could cause us a problem, because PHP is still on the lookout for the ending double quote which wasn’t provided in this code snippet. Even my automatic color coding in the code above is showing a problem, because everything after the quote is blue. Notice in further examples below that this doesn’t happen.
So make sure to keep track of your opening and closing quotes to avoid blowing PHP’s mind.
Missing Dollar Signs
A missing dollar sign in a variable name can be easy to miss. PHP will usually give you a parsing error if you have one, or at the very least your script won’t work.
Incorrect Equal Signs
In PHP, there is a large difference between using one equal sign or two. With one equal sign, you often use it to assign something. For example:
<?php $number = 23; ?>
In this example, we used an equal sign to give $number a value of 23.
However, when we wish to draw a comparison, like in an If Statement, we will use two equal signs. Here’s an example:
<?php if (23 == 23) { echo "23 is in fact equal to 23."; } ?>
So using two equal signs is like asking Is Equal. In this example, we’re asking PHP if 23 is equal to 23. Yes it is, so it will echo out the sentence.
This is a very subtle problem because it won’t always cause PHP to give you an error message. You’ll notice that for some reason your PHP code isn’t working right, even though you’re not receiving an error. If that happens, be sure to double check your equal signs! This may happen to you a lot at first but with time this will be an uncommon mistake. Hopefully!
Misspelled Variable Names
All variables in PHP are case-sensitive. Depending on how your script is setup, PHP may not give an error if you misspell a variable, but it will result in your script not working properly.
Here’s an example of a script that won’t work:
<?php $name = "Mike"; echo $Name; ?>
Notice that $Name is not the same thing as $name, so nothing will be displayed.
This is an easy mistake to make, but it’s also easy to avoid. Many code editors will highlight a variable if you’re trying to use it without giving it a value first. Another way to avoid this is to have a naming convention for your variables so it’s easier to remember how a variable should have been spelled. CamelCase is a popular choice, where you capitalize the beginning of each word in a variable: $FirstName, $HomeOwner, $CuteMonkey, etc.
Missing Semicolons
Every PHP statement must end with a semicolon. If PHP doesn’t see a semicolon, it just keeps reading the code until it does. Check this out:
<?php $firstName = "John"; // we have a semicolon here. $lastName = "Smith" // oops, we're missing a semicolon! echo "My name is $firstName $lastName"; // Should output: My name is John Smith ?>
The missing semicolon on our third line will cause PHP to keep reading into the echo statement and become confused. This would result in an error message like:
Parse error: parse error in localhost\name.php on line 4
Notice that even though the problem (missing semicolon) is in line #3, PHP tells us the error is in line #4. This is because PHP kept reading lines #3 and #4 as one statement.
Missing the Ends
Remember: Parentheses and curly brackets come in twos. If you use an If Statement with its curly bracket {, the end of the If Statement needs to have another bracket } to close it.
To help avoid this problem, indent your code with spaces or tabs. This will help you see where all of your opening and closings belong. For example, which of the following is easier to see?
$number = 123; $name = "Mike"; if ($number == 123) { if ($name == "Mike") { echo "Hi $name!"; } $number + $number = $newNumber; echo $newNumber; } else { echo "Your number is not 123."; }
Or this one?
$number = 123; $name = "Mike"; if ($number == 123) { if ($name == "Mike") { echo "Hi $name!"; } $number + $number = $newNumber; echo $newNumber; } else { echo "Your number is not 123."; }
If you’re like me and most others, then the second set of code lets us easily figure out where our opening and closing brackets belong and relate to each other.
Go back to PHP Debugging and Troubleshooting.
PHP stands for PHP: Hypertext Processor. For more detailed information about what does PHP stand for, visit our What is PHP page.