Thursday 12 July 2012

PHP Functions and Arrays & loops with Example Tutorial


PHP - Functions
A function is just a name we give to a block of code that can be executed whenever we need it. This might not seem like that big of an idea, but believe me, when you understand and use functions you will be able to save a ton of time and write code that is much more readable!
For example, you might have a company motto that you have to display at least once on every webpage. If you don't, then you get fired! Well, being the savvy PHP programmer you are, you think to yourself, "this sounds like a situation where I might need functions."
Tip: Although functions are often thought of as an advanced topic for beginning programmers to learn, if you take it slow and stick with it, functions can be just minor speedbump in your programming career. So don't give up if you functions confuse you at first!
Creating Your First PHP Function
When you create a function, you first need to give it a name, like myCompanyMotto. It's with this function name that you will be able to call upon your function, so make it easy to type and understand.
The actual syntax for creating a function is pretty self-explanatory, but you can be the judge of that. First, you must tell PHP that you want to create a function. You do this by typing the keyword function followed by your function name and some other stuff (which we'll talk about later).
Here is how you would make a function called myCompanyMotto. Note: We still have to fill in the code for myCompanyMotto.
PHP Code:

function myCompanyMotto(){
}
?>
Note: Your function name can start with a letter or underscore "_", but not a number!
With a properly formatted function in place, we can now fill in the code that we want our function to execute. Do you see the curly braces in the above example "{ }"? These braces define where our function's code goes. The opening curly brace "{" tells php that the function's code is starting and a closing curly brace "}" tells PHP that our function is done!
We want our function to print out the company motto each time it's called, so that sounds like it's a job for the echo function!
PHP Code:

function myCompanyMotto(){
echo "We deliver quantity, not quality!
";
}
?>
That's it! You have written your first PHP function from scratch! Notice that the code that appears within a function is just the same as any other PHP code.
Using Your PHP Function
Now that you have completed coding your PHP function, it's time to put it through a test run. Below is a simple PHP script. Let's do two things: add the function code to it and use the function twice.
PHP Code:

echo "Welcome to Tizag.com
";
echo "Well, thanks for stopping by!
";
echo "and remember...
";
?>
PHP Code with Function:

function myCompanyMotto(){
echo "We deliver quantity, not quality!
";
}
echo "Welcome to Tizag.com
";
myCompanyMotto();
echo "Well, thanks for stopping by!
";
echo "and remember...
";
myCompanyMotto();
?>
Display:
Welcome to Tizag.com We deliver quantity, not quality! Well, thanks for stopping by! and remember... We deliver quantity, not quality!
Although this was a simple example, it's important to understand that there is a lot going on and there are a lot of areas to make errors. When you are creating a function, follow these simple guidelines:
• Always start your function with the keyword function
• Remember that your function's code must be between the "{" and the "}"
• When you are using your function, be sure you spell the function name correctly
• Don't give up!
PHP Functions - Parameters
Another useful thing about functions is that you can send them information that the function can then use. Our first function myCompanyMotto isn't all that useful because all it does, and ever will do, is print out a single, unchanging string.
However, if we were to use parameters, then we would be able to add some extra functionality! A parameter appears with the parentheses "( )" and looks just like a normal PHP variable. Let's create a new function that creates a custom greeting based off of a person's name.
Our parameter will be the person's name and our function will concatenate this name onto a greeting string. Here's what the code would look like.
PHP Code with Function:

function myGreeting($firstName){
echo "Hello there ". $firstName . "!
";
}
?>
When we use our myGreeting function we have to send it a string containing someone's name, otherwise it will break. When you add parameters, you also add more responsibility to you, the programmer! Let's call our new function a few times with some common first names.
PHP Code:

function myGreeting($firstName){
echo "Hello there ". $firstName . "!
";
}
myGreeting("Jack");
myGreeting("Ahmed");
myGreeting("Julie");
myGreeting("Charles");
?>
Display:
Hello there Jack! Hello there Ahmed! Hello there Julie! Hello there Charles!
It is also possible to have multiple parameters in a function. To separate multiple parameters PHP uses a comma ",". Let's modify our function to also include last names.
PHP Code:

function myGreeting($firstName, $lastName){
echo "Hello there ". $firstName ." ". $lastName ."!
";
}
myGreeting("Jack", "Black");
myGreeting("Ahmed", "Zewail");
myGreeting("Julie", "Roberts");
myGreeting("Charles", "Schwab");
?>
Display:
Hello there Jack Black! Hello there Ahmed Zewail! Hello there Julie Roberts! Hello there Charles Schwab!
PHP Functions - Returning Values
Besides being able to pass functions information, you can also have them return a value. However, a function can only return one thing, although that thing can be any integer, float, array, string, etc. that you choose!
How does it return a value though? Well, when the function is used and finishes executing, it sort of changes from being a function name into being a value. To capture this value you can set a variable equal to the function. Something like:
• $myVar = somefunction();
Let's demonstrate this returning of a value by using a simple function that returns the sum of two integers.
PHP Code:

function mySum($numX, $numY){
$total = $numX + $numY;
return $total;
}
$myNumber = 0;
echo "Before the function, myNumber = ". $myNumber ."
";
$myNumber = mySum(3, 4); // Store the result of mySum in $myNumber
echo "After the function, myNumber = " . $myNumber ."
";
?>
Display:
Before the function, myNumber = 0 After the function, myNumber = 7
When we first print out the value of $myNumber it is still set to the original value of 0. However, when we set $myNumber equal to the function mySum, $myNumber is set equal to mySum's result. In this case, the result was 3 + 4 = 7, which was successfully stored into $myNumber and displayed in the second echo statement!
PHP Functions - Practice Makes Perfect
If you are new to programming, then this lesson might or might not seem like overkill. If you are having a hard time understanding lessons, the best piece of advice would be to do your best the first time, then be sure to come back tomorrow and next week and see if it makes anymore sense. Chances are, after going through this tutorial more than once, with breaks in between, this topic will be mastered.
PHP - Arrays
An array is a data structure that stores one or more values in a single value. For experienced programmers it is important to note that PHP's arrays are actually maps (each key is mapped to a value).
PHP - A Numerically Indexed Array
If this is your first time seeing an array, then you may not quite understand the concept of an array. Imagine that you own a business and you want to store the names of all your employees in a PHP variable. How would you go about this?
It wouldn't make much sense to have to store each name in its own variable. Instead, it would be nice to store all the employee names inside of a single variable. This can be done, and we show you how below.
PHP Code:
$employee_array[0] = "Bob";
$employee_array[1] = "Sally";
$employee_array[2] = "Charlie";
$employee_array[3] = "Clare";
In the above example we made use of the key / value structure of an array. The keys were the numbers we specified in the array and the values were the names of the employees. Each key of an array represents a value that we can manipulate and reference. The general form for setting the key of an array equal to a value is:
• $array[key] = value;
If we wanted to reference the values that we stored into our array, the following PHP code would get the job done.
PHP Code:
echo "Two of my employees are "
. $employee_array[0] . " & " . $employee_array[1];
echo "
Two more employees of mine are "
. $employee_array[2] . " & " . $employee_array[3];
Display:
Two of my employees are Bob & Sally Two more employees of mine are Charlie & Clare
PHP arrays are quite useful when used in conjunction with loops, which we will talk about in a later lesson. Above we showed an example of an array that made use of integers for the keys (a numerically indexed array). However, you can also specify a string as the key, which is referred to as an associative array.
PHP - Associative Arrays
In an associative array a key is associated with a value. If you wanted to store the salaries of your employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.
PHP Code:
$salaries["Bob"] = 2000;
$salaries["Sally"] = 4000;
$salaries["Charlie"] = 600;
$salaries["Clare"] = 0;
echo "Bob is being paid - $" . $salaries["Bob"] . "
";
echo "Sally is being paid - $" . $salaries["Sally"] . "
";
echo "Charlie is being paid - $" . $salaries["Charlie"] . "
";
echo "Clare is being paid - $" . $salaries["Clare"];
Display:
Bob is being paid - $2000 Sally is being paid - $4000 Charlie is being paid - $600 Clare is being paid - $0
Once again, the usefulness of arrays will become more apparent once you have knowledge of for and while loops.
PHP - While Loop
Repetitive tasks are always a burden to us. Deleting spam email, sealing 50 envelopes, and going to work are all examples of tasks that are repeated. The nice thing about programming is that you can avoid such repetitive tasks with a little bit of extra thinking. Most often these repetitive tasks are conquered in the loop.
The idea of a loop is to do something over and over again until the task has been completed. Before we show a real example of when you might need one, let's go over the structure of the PHP while loop.
Simple While Loop Example
The function of the while loop is to do a task over and over as long as the specified conditional statement is true. This logical check is the same as the one that appears in a PHP if statement to determine if it is true or false. Here is the basic structure of a PHP while loop:
Pseudo PHP Code:
while ( conditional statement is true){
//do this code;
}
This isn't valid PHP code, but it displays how the while loop is structured. Here is the break down of how a while loop functions when your script is executing:
1. The conditional statement is checked. If it is true, then (2) occurs. If it is false, then (4) occurs.
2. The code within the while loop is executed.
3. The process starts again at (1). Effectively "looping" back.
4. If the conditional statement is false, then the code within is not executed and there is no more looping. The code following the while loop is then executed like normal.
A Real While Loop Example
Imagine that you are running an art supply store. You would like to print out the price chart for number of brushes and total cost. You sell brushes at a flat rate, but would like to display how much different quantities would cost. This will save your customers from having to do the mental math themselves.
You know that a while loop would be perfect for this repetitive and boring task. Here is how to go about doing it.
Pseudo PHP Code:
$brush_price = 5;
$counter = 10;
echo "
";
echo "
";
echo "
";
while ( $counter <= 100 ) {
echo "
";
$counter = $counter + 10;
}
echo "
QuantityPrice
";
echo $counter;
echo "
";
echo $brush_price * $counter;
echo "
";
Display:
Quantity
Price
10
50
20
100
30
150
40
200
50
250
60
300
70
350
80
400
90
450
100
500
Pretty neat, huh? The loop created a new table row and its respective entries for each quantity, until our counter variable grew past the size of 100. When it grew past 100 our conditional statement failed and the loop stopped being used. Let's review what is going on.
1. We first made a $brush_price and $counter variable and set them equal to our desired values.
2. The table was set up with the beginning table tag and the table headers.
3. The while loop conditional statement was checked, and $counter (10) was indeed smaller or equal to 100.
4. The code inside the while loop was executed, creating a new table row for the price of 10 brushes.
5. We then added 10 to $counter to bring the value to 20.
6. The loop started over again at step 3, until $counter grew larger than 100.
7. After the loop had completed, we ended the table.
You may have noticed that we placed slashes infront the quotations in the first echo statement. You have to place slashes before quotations if you do not want the quotation to act as the end of the echo statement. This is called escaping a character and it is discussed in our PHP Strings lesson.
With proper use of loops you can complete large tasks with great ease.
PHP - For Loop
The for loop is simply a while loop with a bit more code added to it. The common tasks that are covered by a for loop are:
1. Set a counter variable to some initial value.
2. Check to see if the conditional statement is true.
3. Execute the code within the loop.
4. Increment a counter at the end of each iteration through the loop.
The for loop allows you to define these steps in one easy line of code. It may seem to have a strange form, so pay close attention to the syntax used!
For Loop Example
Let us take the example from the while loop lesson and see how it could be done in a for loop. The basic structure of the for loop is as follows:
Pseudo PHP Code:
for ( initialize a counter; conditional statement; increment a counter){
do this code;
}
Notice how all the steps of the loop are taken care of in the for loop statement. Each step is separated by a semicolon: initiliaze counter, conditional statement, and the counter increment. A semicolon is needed because these are separate expressions. However, notice that a semicolon is not needed after the "increment counter" expression.
Here is the example of the brush prices done with a for loop .
PHP Code:
$brush_price = 5;
echo "
";
echo "
";
echo "
";
for ( $counter = 10; $counter <= 100; $counter += 10) {
echo "
";
}
echo "
QuantityPrice
";
echo $counter;
echo "
";
echo $brush_price * $counter;
echo "
";
Display:
Quantity
Price
10
50
20
100
30
150
40
200
50
250
60
300
70
350
80
400
90
450
100
500
It is important to note that both the for loop and while loop implementation of the price chart table are both OK at getting the job done. However, the for loop is somewhat more compact and would be preferable in this situation. In later lessons we will see where the while loop should be used instead of the for loop.
PHP For Each Loop
Imagine that you have an associative array that you want to iterate through. PHP provides an easy way to use every element of an array with the Foreach statement.
In plain english this statement will do the following:
• For each item in the specified array execute this code.
While a For Loop and While Loop will continue until some condition fails, the For Each loop will continue until it has gone through every item in the array.
PHP For Each: Example
We have an associative array that stores the names of people in our company as the keys with the values being their age. We want to know how old everyone is at work so we use a Foreach loop to print out everyone's name and age.
PHP Code:
$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";
foreach( $employeeAges as $key => $value){
echo "Name: $key, Age: $value
";
}
Display:
Name: Lisa, Age: 28 Name: Jack, Age: 16 Name: Ryan, Age: 35 Name: Rachel, Age: 46 Name: Grace, Age: 34
The syntax of the foreach statement is a little strange, so let's talk about it some.
Foreach Syntax: $something as $key => $value
This crazy statement roughly translates into: For each element of the $employeeAges associative array I want to refer to the key as $key and the value as $value.
The operator "=>" represents the relationship between a key and value. You can imagine that the key points => to the value. In our example we named the key $key and the value $value. However, it might be easier to think of it as $name and $age. Below our example does this and notice how the output is identical because we only changed the variable names that refer to the keys and values.
PHP Code:
$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";
foreach( $employeeAges as $name => $age){
echo "Name: $name, Age: $age
";
}
Display:
Name: Lisa, Age: 28 Name: Jack, Age: 16 Name: Ryan, Age: 35 Name: Rachel, Age: 46 Name: Grace, Age: 34
PHP - Do While Loop
A "do while" loop is a slightly modified version of the while loop. If you recal from one of the previous lessons on While Loops the conditional statement is checked comes back true then the code within the while loop is executed. If the conditional statement is false then the code within the loop is not executed.
On the other hand, a do-while loop always executes its block of code at least once. This is because the conditional statement is not checked until after the contained code has been executed.
PHP - While Loop and Do While Loop Contrast
A simple example that illustrates the difference between these two loop types is a conditional statement that is always false. First the while loop:
PHP Code:
$cookies = 0;
while($cookies > 1){
echo "Mmmmm...I love cookies! *munch munch munch*";
}
Display:
As you can see, this while loop's conditional statement failed (0 is not greater than 1), which means the code within the while loop was not executed. Now, can you guess what will happen with a do-while loop?
PHP Code:
$cookies = 0;
do {
echo "Mmmmm...I love cookies! *munch munch munch*";
} while ($cookies > 1);
Display:
Mmmmm...I love cookies! *munch munch munch*
The code segment "Mmmm...I love cookies!" was executed even though the conditional statement was false. This is because a do-while loop first do's and secondly checks the while condition!
Chances are you will not need to use a do while loop in most of your PHP programming, but it is good to know it's there!

No comments:

Post a Comment