It feels like everything in PHP is a function, yes?
I mean, it functions, right?
Well, this definition of “functions” is a little bit different.
A FUNCTION in PHP is really quite easy to understand -
It is a chunk of code (like a “snippet”, if you are familiar with that term) that can be named and reused at any time.
Remember earlier when we were talking about repetitive tasks?
Functions can help us further reduce these time-killers by writing a block of code once, then defining it as a function. Kinda like a great big variable.
Here’s how it works:
<?php
function MyFunctionName(){
//define your function here
}
?>
Functions are quite cool, because they can be considered building blocks of a web application.
Let’s say you want every page of a website to say your company name.
Let’s create a function to do so. Let’s call it myCompanyName.
<?php
function myCompanyName(){
}
?>
Now, let’s add the code we want to execute between the curly brackets:
<?php
function myCompanyName(){
echo "Welcome to The Creamy Bagel Company!<br />";
}
?>
So now whenever we want our company name to appear, you can call the function within a PHP tag anywhere!
<?php
function myCompanyName(){
echo "Welcome to The Creamy Bagel Company!<br />";
}
echo “Isn’t it about time you experienced a better bagel?<br />”;
myCompanyName();
?>
A Function can contain just about any type of PHP code, so I hope you can see how useful this can be - it can definitely be a timesaver when working with a lot of code.
0 Comments
What if you want to loop through an Associative Array?
The FOR LOOP is very similar to a WHILE LOOP. The Creamy Bagel Company wants to show a pricing matrix on their website for up to a 20 bagel pack. But, since bagels are a valuable commodity, the price fluctuates regularly. Note on PHP Math functions We all have mundane, repetitive tasks we have to do. An Associative Array is an array in which the keys are associated with values. An Array can be thought of as a single variable that stores more than one value. Sometimes we have to evaluate more than just a few cases, making ElseIf a tad cumbersome (do YOU want to write 20 ElseIf’s? I don’t!) The IF/ELSE statement is wonderful if you need to check for only one condition. You could create a simple password protected area using If/Else. |
David Rentson
If this free PHP and MYSQL Tutorial is helpful for you... Great! Archives
October 2008
Categories
All
|