Thanks for the tips but can you recommend more advanced php lessons?
A Quick Guide to PHP Functions.
What is a function?
A function is a way of repeating PHP code over and over again quickly and easily. Instead of having 20 lines of code repeated 5 times, you use the 20 lines of code once, and repeat 1 line of code 5 times.
Ok. Now you understand exactly why functions are so useful, I’ll go into a bit more detail about how they can be used.
To create a function, type:
And all the code for the function goes in between those curly braces.PHP Code:function name {
}
You can have a simple function like this:
And then you can call it:PHP Code:function random() {
return rand (1, 5);
}
And you will get a random number between 1-5. Now, in-between those brackets you can have parameters. This may confuse you at first, but once you get it it is very easy.PHP Code:random();
Just take a minute to read it over. Remember in the last function, the random function was between 1 and 5? Now, it will be between $min and $max. How do we assign $min and $max? When we call for the function:PHP Code:function random($min, $max) {
return rand ($min, $max);
}
It will give you a random number between 5 and 10. All I have done when calling the function is replaced $min with 5, and $max with 10.PHP Code:random(5, 10);
If you want to assign the function to a variable, you can easily, just like you would for most variables.
Let’s make things a bit more complex. Readers of my ‘Beginning PHP’ will be familiar with this example. I want to work out the area of my rectangle, and the perimeter. Now, knowing what we do about parameters within functions, you should understand this code:PHP Code:$variable = random(5, 10);
Slightly confused? I’m going to show the same function again, but replace $width and $height with a number, which should help you out.PHP Code:function rectangle($width, $height) {
$area = $width * $height;
$perim = ($width + $height) * 2;
echo ‘<h4>Area is: ‘.$area.’</h4>’;
echo ‘<h4>Perimeter is: ‘.$perim.’</h4>’;
}
Hopefully that is clear to you know. To call on the function, and assign the width and height values, we do:PHP Code:function rectangle(3, 5) {
$area = 3 * 5;
$perim = (3 + 5) * 2;
echo ‘<h4>Area is: 15 </h4>’;
echo ‘<h4>Perimeter is: 16</h4>’;
}
That concludes a brief tour of functions. Hopefully you now understand how to create a function, how to call a function, and how functions spare PHP developers a lot of time.PHP Code:rectangle (5, 10);
Remember – It’s not about reading this, to learn anything you must type the code out for yourself.
Jack
Thanks for the tips but can you recommend more advanced php lessons?
Last edited by damienb; 11-18-2010 at 10:20 AM.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks