-
A journey leads to php....
The FOR LOOP
The FOR LOOP is very similar to a WHILE LOOP. The difference being a little bit more code is contained in the loop. The FOR LOOP can be a little more compact than a WHILE LOOP. Here’s the logic:
for ( create a counter; conditional statement; increment the counter){
do this;
}
Let’s use our fluctuating bagel cost from above and write this out. Oops - bagels just went up 10 cents!
<?php
$bagel_price = 2.25;
echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>Quantity</th>";
echo "<th>Price</th></tr>";
for ( $counter = 1; $counter <= 20; $counter += 1) {
echo "<tr><td>";
echo $counter;
echo "</td><td>";
echo $bagel_price * $counter;
echo "</td></tr>";
}
echo "</table>";
?>
Once again, the loop is highlighted in blue. You’ll notice that the counter is defined inside the loop as opposed to a variable outside.
And..to the right, you’ll see the output.
There’s one more Loop we’re going to cover, isn’t this exciting? Hello? Still there?
The FOR EACH Loop
What if you want to loop through an Associative Array? (See? Told you we’d get back to this!) You can use FOR EACH to do this task. Where the WHILE and FOR loops run until an error is encountered, the FOR EACH loop will run through every element in the array.
Let’s revisit the associative array we set up with the trucks...
<?php
$truck[“Toyota”] = Tundra;
$truck[“Nissan”] = Titan;
$truck[“Dodge”] = Ram;
?>
To loop through the Makers / Models, we’d use this code:
<?php
foreach( $truck as $make => $model){
echo "Make: $make, Model: $model <br />";
}
?>
The code is written in a strange way, it isn’t obvious how it works. Let’s look at it in a simpler way:
$something as $key => $value
So, in english... FOR each thing in the array, I want to refer to the key as $key and the value as $value. The operator ‘=>’ indicates the relationship between the key and the value...the key “points” to the value.
I think that’s about all we need to cover with Loops.
Next up...
-
A journey leads to php....
What’s your FUNCTION?
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();
?>
Output looks like this...
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.
-
A journey leads to php....
PHP SESSIONS
When your websites start to become more advanced and you find that you have a need for specific user data to be available throughout different pages on your website (think shopping cart!), it’s time for Sessions!
Starting a session is a snap.
<?php
session start();
?>
The webserver will attach a really really long random “session ID” to indicate a unique session. It looks something like: a8486dd2a3eacc136bd44ca653d8c5a2
A session isn’t worth a hill of beans unless we can store data in it. Fortunately, PHP can do this for us with an associative
array, based on the $_SESSION variable. (Is some of this starting to come together?)
Let’s make a login form based on sessions!
<?php
session_start(); // Starts a PHP session
echo "<form method=POST action=index.php>
User Name: <input type=text name=\"username\">
Password: <input type=text name=\"password\">
<input type=submit>
</form>"; // This is the HTML form
$_SESSION['username']=$_POST["username"]; // Enters the username into the array
$_SESSION['password']=$_POST["password"]; // Enters the password into the array
?>
Your username and password are now stored in an array that will last until the session is “un-set”.
Removing a session is done when either: The viewer closes their browser, or PHP runs the command to un-set a session, aka “destroy”.
You can think of it like this - your session is an Etch-a-Sketchtm that has information drawn on it. It’s there until you shake it!
<?php
session_destroy();
?>
Yes, it’s a tad violent...but gets the job done. This will clear out any data associated with the current session.
So, what if I want to remove specific data from a session without deleting the whole thing?
This can be done with an IF statement combined with commands called “ISSET” and “UNSET”.
<?php
if(isset($_SESSION['items'])){
unset($_SESSION['items']);}
?>
So, logically...
If this specific key is set in this session, remove the key’s data.
-
A journey leads to php....
Cookies (mmmmmm!)
You are hopefully familiar with Cookies - you get them almost anytime you visit a website. Cookies allow you to store information about your visitor’s session on their computer.
One of the most common uses of cookies is to store usernames. That way when a viewer returns to your site, they don’t have to log in each time they visit.
You can create cookies in PHP with:
<?php
setcookie(name, value, expiration);
?>
There are 3 requirements when setting a cookie:
• Name: This is where you set the name of your cookie so you can retrieve it later.
• Value: The value you wish to store in your cookie. Some common values are usernames or date last visited.
• Expiration: When your cookie will be deleted from the user’s computer. If you do not set an expiration date, the cookie will be deleted when the viewer closes their browser!
Getting information from a cookie is just about as easy as setting one. Remember the “ISSET” stuff a few minutes ago? PHP gets cookie data in a similar way, by creating an associative array (Yes, again!) to store your retrieved cookie data...using the $_COOKIE variable. The array key is what you named the variable when it was set (so, obviously you can set any number of cookies!) So... (next page please!)
<?php
if(isset($_COOKIE['username'])){ // If there’s a cookie...
$username = $_COOKIE['username']; // set the variable...
echo "Welcome back, $username."; // and show the data in the cookie...
} else {
echo "No username was found. Sorry!";} // or show this if there wasn’t one.
?>
And, FYI...Cookies are stored as small text files on your computer (in case you did not know!)
And now...one of the most useful functions of PHP...
-
A journey leads to php....
PROCESSING FORMS
What is one thing almost everyone wants to do with their website? Have a contact form. And, it isn’t as difficult as you’d think. We’re going to use the PHP mail() command to make one.
Make an HTML form with Name, Email and Message fields. Take the code below and place it in a PHP file to use as your action.
<?php
mail("[email protected]", "Form Feedback", " // your address and subject
Name: $name
Email: $email
Message: $message
", "From: $email");
// Display results
echo("
<html>
Name: $name
Email: $email
Message: $message
</html>
");
?>
Section Two Overview
In this section, we covered some more advanced features of PHP. Not for the timid, but not impossible to grasp!
IF - Do something if something is true.
ELSE - Do something else if it isn’t
ELSEIF - Add more choices to IF
SWITCH - Use this if you have a lot of ElseIf’s
ARRAY - One variable, many values
ASSOCIATIVE ARRAY - One variable, even more values
LOOPS - For, While, For Each - A way to repeat code
FUNCTIONS - Turn a big code chunk into a small one
SESSIONS - Carry unique data from page to page
COOKIES - Store session data on your viewer’s computer
FORM PROCESSING - Process web forms, such as a mailer
QUIZ
1. What are the 3 ways to comment code in PHP?
2. ELSEIF cannot be used without __
3. What are Cookies used for in PHP?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
Bookmarks