In the previous chapter you learned what PHP was, had a passing brush with its history, and had a peek at just what it was capable of. In this chapter I’m going to teach you two basic elements of coding in PHP: functions and variables.
Variables
What is a variable?
The easiest way to define a variable is take a look in your storage closet or attic (stick with me here, I haven’t quite lost my marbles). Chances are you’ll find boxes of things, and some of them will have labels. They’ll probably contain things like last year’s Christmas decorations, or the clothes that don’t fit anymore (in a fit of self-denial, I labeled that box as ‘The Damn Machine Shrunk My Clothes’), or old books, or heck, the box could be even be empty.
A variable is much like one of those boxes. The only difference is that there is no size limit. Each variable has a variable name (like the label on the box) and may have something stored in it, which in PHP is known as the variable’s value. And like your boxes, a variable can store anything from strings of text (for example, your house address) to numbers (for example, the amount of tax you owe the IRS. Yikes.).
So why use variables?
Let’s say you have a 6 beach balls, 2 old bathing suits, and an old summer hat that makes you wonder what you were thinking. If you were to rearrange your storage closet, you’d have to move each individual item. How about if you were going to bring it out into the living room? Or sent it to a local charity? Yup, you’d have to move each thing one by one.
However, if you were to put it in a box (let’s call it the ’summer’ box) , you’d only have to move one item: the box. Instantly you’ve cut down the amount of tedious effort required by only doing one task instead of nine. Variables are much the same. Instead of typing the same values again and again and again, you just assign it to a variable, and then use that variable in your code. Also, if that number happens to change, you only have to change it at one point in your code.
Another good reason to use variables is a no-brainer: they’re variable (get it? No? Dang.). The value that they represent can change, and you may not always know what that value is. Say you’re making an online survey. You won’t know what your user’s answer is, so it’s impossible to write a code that records that answer. Instead, you tell PHP to assign the user’s answer to a variable (perhaps we’ll call it $answer) and then you use this variable name in your code.
How do I write a variable?
If you liked math or algebra in school, this’ll be a breeze.
<?php $variablename = 'value'; ?>
Seriously, it’s that simple. Here’s a breakdown of the process.
- Write the dollar sign ($). The dollar sign is required for all variable names in PHP.
- Write your variable’s name. As with all other aspects of PHP coding (and with all other languages, really), name it something relevant to its value. ‘$something’ can mean anything, but ‘$amount_due’ would be much clearer. This will help you out a lot when you’re juggling 20-30 different variables and you can’t remember what each one holds.
- Use the assignment operator, which is really just a fancy programmer way of referring to the equals sign (=).
- Write in your value. If your value is a string, you’ll want to enclose it with either single quote marks (”) or double quote marks (”"). If your value is an integer, then go right ahead and write it in without any quote marks.
- End your value with a semi-colon (;). The semi-colon is used to end the line that you’re writing, so in this case it means you’re done telling PHP what this variable holds. This is a necessary step and can often trip you up, as it’s tiny and can be rather hard to spot.
What should I watch out for when writing a variable?
- Always remember the dollar sign.
- Variable names can only start with letters or an underscore (_).
- Variable names can only contain letters, numbers, and underscores. No special characters or spaces allowed.
- When you’re assigning a value to a variable, you have to use the assignment operator (=).
- Use names that are relevant. PHP won’t stop you from naming your variables after your pets or celebrities, but if you’re sharing your code with someone, or if you revisit this code later on, it may be a bit tricky figuring out what values you assigned to $foofy_the_chihuahua or $gloriaEstefan.
- Variable names are case-sensitive. I cannot stress this enough. ‘$number’ and ‘$Number’ are two different variables, and PHP will treat them as such.
- Some programmers prefer to use a combination of uppercase and lowercase letters (e.g.: $variableName) instead of underscores (e.g.: $variable_name). You may even find some variables in all lowercase (e.g.: $variablename). It’s a personal preference and either one is fine to use, but it’s a good idea to maintain a consistent pattern throughout your codes. For sake of clarity, however, I suggest you avoid the third option. Compare $birdsHit, $birds_hit, and $birdshit, and you’ll understand why.
How do I use a variable?
To use a variable, all you have to do is call it by the name you gave it. For example:
<?php $number = 6; $myname = 'Ash'; echo($number); //This will display the number 6. echo($myname); //This will display the string 'Ash'. ?>
If you feel like you don’t like the number 6 (or if, for some bizarre reason, your name isn’t Ash), all you have to do is to change the values in the first two lines, where we assigned the values. The next time you run the script, the number you prefer and your name will be displayed instead. But seriously, you mean everyone isn’t named Ash?
Examples of variables
<?php
$name = "Ash";
$age = 20; //Yeah, right.
$_hobbies = array('design', 'art', 'music', 'dance');
//Don't be alarmed by this strange new 'array' word. I'll be covering it coming chapters.
$favourite_quote = "Everything's okay in the end. If it's not okay, it's not the end.";
$what_I_suspected_my_fourth_grade_teacher_was = "A penguin who learnt to speak English.";
?>
Have fun experimenting with variables and what you can do with them, it’s a great way to practice writing them.
Functions
What is a function?
Imagine telling Person A to do something, such as sweeping the floor. In order for this to happen, two conditions must be fulfilled:
- Person A must actually know what ’sweep the floor’ means, and
- You must tell Person A to sweep the floor.
No seriously, I actually know people who don’t know what sweeping the floor means. Using functions in PHP is pretty much the same thing, only we don’t assume that Person A knows what ’sweep the floor’ means, so we explain it for them. In PHP (and in many other programming languages), this is called defining or declaring a function.
Once we’ve explained to Person A about this magical art of sweeping, we must then make sure we actually TELL Person A to sweep the floor. After all, PHP assumes nothing, so just because you declare a function doesn’t mean you’re actually going to use it. In PHP, using a function that you declared is known as calling a function.
Functions are one of the building blocks of almost every PHP script you will find, so a solid understanding of the idea behind it will really help you later on.
How do I declare a function?
The basic syntax for defining a function is extremely simple:
<?php
function functionname(){
//The code goes here.
};
?>
- First, write the word ‘function’, which tells PHP that you’re declaring a new function.
- Then, add a space, and type in the name of the function. It can be anything you want, with some exceptions (which I’ll be covering later on in this chapter). You’ll be using this name to call the function later on, so it’s a good idea to name it something relevant to the function’s purpose.
- Insert a closed pair of parentheses ‘()’ after the function name. The space between those parentheses is used for parameters, which I’ll be covering further on in this chapter.
- Add a left curly bracket ‘{’.
- Type in the code that tells PHP what to do when this function is called. In can be as many lines as you want, and can tell PHP to do anything.
- Add a right curly bracket to close ‘}’.
- As a best practice, add a semi-colon ‘;’ after step 6. It’s not necessary here, since the closing curly bracket already defines where the function’s codes stop, but it’s necessary for some other codes, and it’s a good habit to establish.
What should I watch out for when declaring a function?
The rules for declaring a variable can pretty much be applied here too. Of course, instead of using the dollar sign, functions use the ‘function’ keyword. Like variables, you can only start with letters or an underscore, and can only contain letters, underscores, and numbers. Function names are also case-sensitive. Like variables, it’s a good idea to name your functions something relevant (in this case, relevant to what task they perform). And I think you already know the last bit about uppercase and lowercase naming, so I’ll avoid making any more lame birdshit jokes.
How do I call a function?
You call a function by calling it’s name, and then a closed pair of parentheses, like so:
<?php functionname(); ?>
Remember, you don’t have to write the word ‘function’ any more, since you’re not declaring it.
What are parameters?
To explain what parameters are, I’m going to give you an example. Let’s say you’re in charge of a class of second-graders. There are forty of them. And for each one student, you have to write the following line:
“Ash is a boy.”
Of course, you’d have to substitute ‘Ash’ for the name of the student, and if the student was a girl, you’d have to change that bit, too. If you didn’t know about functions, you’d have to do it this way:
<?php
echo('Ash is a boy.');
echo('Katie is a girl.');
echo('Jimmy is a boy.');
?>
And so on, and so on, which would be extremely time-consuming. Now that you know how to use functions, however, you could just do it like this:
<?php
function isBoy(){
echo ' is a boy';
};
function isGirl(){
echo ' is a girl.';
};
echo 'Ash';
isBoy();
echo 'Katie';
isGirl();
?>
Which helps ever so slightly, but now you have to write two eighty lines instead of fourty. Not very helpful, then.
This is where parameters come in handy. Parameters are basically variables that you pass to a function, to give it some information. You use parameters like so:
<?php
function functionname($parameter1, $parameter2){
//Your code goes here.
};
?>
You can have as many parameters as you like. For the next part of the example, we’re going to use two.
<?php
function introduce_student($name, $gender){
echo ($name . ' is a ' . $gender . '.');
};
?>
When we put $name and $gender within the parentheses, PHP treats them as variables while it’s performing the function. This means that you can use them as if they were regular variables like the ones you just learnt earlier. In this case what I’ve done is created a function called introduce_student, which takes two parameters, a name, and a gender. When called, the function displays the following: the name that I provided, followed by the phrase ‘ is a ‘, and then the gender that I provided, and finally a period. The other periods that you see scattered among the line are used to join two values together. In this case, we join a variable with a string, and then another variable, and finally another string (the actual period). Also do note that I’ve put spaces inside the string. Otherwise, your sentences would come out looking like ‘Ashisaboy.’.
So how do you use this newfound power of yours? Like so:
<?php
introduce_student('Ash', 'boy');
introduce_student('Katie', 'girl');
?>
You insert two string values (the name, and the gender) when calling the function. PHP will then proceed to use those two string values as $name and $gender within the function, and will proceed accordingly. You can also use variables as parameters, like so:
<?php $name1 = 'Ash'; $gender1 = 'boy'; introduce_student($name1, $gender1); ?>
Now you’re back to forty lines, and only one function. You can shorten it even further, in fact, by giving the function a shorter name than ‘introduce_student’.
There’s one more aspect to parameters that you should learn, and I’ll make things interesting. Let’s say that Ash and Jimmy are the only two boys in the class. If you’ve been keeping track, that means there are 38 girls in the class. A happy story indeed. But that means you’ll have to write the word ‘girl’ 38 times when writing your function.
This is where parameters have a hidden trick up their sleeve. You can specify a default value for a parameter when declaring the function, by doing so:
<?php
function introduce_student($name, $gender = 'girl'){
echo ($name . ' is a ' . $gender . '.');
};
?>
Basically you’re telling PHP to assume that the value of $gender is ‘girl’ unless stated otherwise. So for Katie and the rest of the girls, all you’d have to write is this:
<?php
introduce_student('Katie');
?>
And for Ash and Jimmy, you’d write it this way:
<?php
introduce_student('Ash', 'boy');
introduce_student('Jimmy', 'boy');
?>
Parameters that have default values are called optional parameters, while parameters that don’t are called required parameters. The names are self-explanatory: you are required to put a value or a variable for each of the required parameters when calling a function, but you have the option of not doing so for the optional parameters.
There are two important rules when using parameters. Firstly, when declaring a function, all the required parameters must come before all the optional parameters. If you think about it, it makes sense. Let’s take for example this function:
<?php
function describe_cat($name, $body_color, $paw_color = 'white', $tail_color){
//Do some code that describes the cat.
};
?>
If you look at it, you’ll see that the function has three required parameters, and one optional one. So by logic, you could call the function like this:
<?php
describe_cat('Purrzilla', 'brown', 'black');
?>
But how would PHP know which part of the cat is colored brown, or black? When calling functions, you must supply the parameters in the order that you declared them. So in this case, PHP assumes that you’ve supplied values for $name, $body_color, and $paw_color. It then sees that there is no value for $tail_color, and will show an error.
PHP helps prevent this mess from happening somewhat by requiring that when you declare a function, all required parameters must come first. So if you do this:
<?php
function describe_cat($name, $body_color, $tail_color, $paw_color = 'white'){
//Do some code that describes the cat.
};
describe_cat('Purrzilla', 'brown', 'black');
?>
PHP will accept the three values for the three required parameters, and will take the default value ‘white’ for the fourth parameter, $paw_color. It will then describe a cat that named Purrzilla that has a brown body, black tail, and white paws. How’s that for funky?
The second rule is basically an extension of the first one. Let’s say I change the previous function:
<?php
function describe_cat($name, $body_color = 'brown', $tail_color = 'black', $paw_color = 'white'){
//Do some code that describes the cat.
};
?>
If you had this function, all you’d have to do is to call the function with the cat’s name, and you’d be good to do. But what if the cat’s paws are pink? Look at the next bit of code:
<?php
describe_cat('Purrzilla', 'pink');
?>
Would that work? Nope, you guessed it. PHP would assume that ‘pink’ is the value for $body_color, and would give you a pink-bodied cat. Ew. It’s not possible for you to skip one or more optional variables to specify another one further down the road. If you want to specify the value for $paw_color, you’ll have to specify the values for $body_color and $tail_color as well. You only have to specify values for the ones before the one that you want, so for example if you wanted to specify a value for $tail_color, you’d only have to specify a value for $body_color as well. Keep this in mind when writing your functions, as it will save you a lot of headache.
Coming Soon
I hope you’ve benefited from this tutorial, even if it’s in some small way. In the next chapter, I’ll be covering two more essential PHP building blocks: arrays, and classes. Meanwhile, if you have any questions about this tutorial, or any suggestions on how I can improve my tutorials in general, do let me know in the comments, and I’ll be extremely grateful!
Other posts in the series
- Beginner PHP Chapter 4 - Conditional Statements - July 23, 2010
- Beginner PHP Chapter 3 - Operators - June 3, 2010
- Beginner PHP Chapter 2 – Functions and Variables (This post) - May 23, 2010
- Beginner PHP Chapter 1 – The Meet n’ Greet - April 16, 2010
