php basic (part II)

Posted Sep 01, 2009 by terninator / comments 0 comments / Print / Font Size Decrease font size Increase font size

Lesson 08 - Control structure, foreach loop Lesson 09 - Control structure, while loop Lesson 10 - Basics of user input Lesson 11 - Using user input Lesson 12 - Using functions Lesson 13 - Creating custom functions

Lesson 08 - control structure, foreach loop

The second type of control structure we're going to discuss is the "foreach" loop. The "foreach" loop allows you to iterate over each value of an array. The "foreach" loop has two syntaxes, one for arrays you might have initialized, and one more specifically for associated arrays which you might have initialized. Here are the syntaxes for both:

foreach (array_expression as $value) { do something with $value }
foreach (array_expression as $key => $value) { do something with $key and $value }

Let's take our example from lesson 5:

Code: [Select]
$people = array('Parham','Jeff','Joseph','Unknown','David','Alex');

As you can see, we've declared an array called $people which store the names of a few people. While you can get access each element using $people[0 to 5] (as we discussed in our array lesson), if you didn't know how big the array was, you'd never know how far to go. There is a combination of a loop and a function you could use, but for now, this is the SIMPLEST way to iterate through an entire array. Let's use the above array and the above "foreach" loop syntax to write out a simple example:

Code: [Select]
$people = array('Parham','Jeff','Joseph','Unknown','David','Alex');
foreach ($people as $person) { //note the singular and plural variable names
echo "$person\n";
}

The above "foreach" loop says the following: "foreach element (person) in the array (people), print the element (person's name)". The example above will have the following output:

"Parham
Jeff
Joseph
Unknown
David
Alex"

Of course you don't just have to print out each value in the array. There are endless possibilities of what you can do with each value in the array. I just think that printing each element is the easiest and therefore will show you the most clearly how to use a "foreach" loop. Let's do the same thing with the associated array syntax:

Code: [Select]
$people = array('person1' => 'Parham','person2' => 'Jeff','person3' => 'Joseph','person4' => 'Unknown','person5' => 'David','person6' => 'Alex');
foreach ($people as $person => $name) { //again note the singular and plural variables names
echo "$person - $name\n";
}

The example above will have the following output:

"person1 - Parham
person2 - Jeff
person3 - Joseph
person4 - Unknown
person5 - David
person6 - Alex"

That's about it for the "foreach" loop. So you might ask why is the "foreach" loop called a control structure. Well that's because PHP will run the block of code as many times as there are elements in the array. It will execute the block, move back up, and execute again until all the elements are dealt with.

That's about it for the "foreach" loop. Hopefully those of you reading the tutorials aren't finding these hard or complicated to understand. The lessons at this point might seem a little like they're all over the place, but by the time the main lessons are complete, I'll demonstrate putting all these lessons together to create simple programs. For those of you that really want to learn, expect homework after the main lessons are done. The homework won't be at all complicated or tricky, but it will help you understand some of PHP's features better. I WILL check all programs you guys write so I know you're on the right track.

Lesson 09 - control structure, while loop

In the last lesson we discussed the "foreach" loop which in my opinion is the simplest type of loop. A lot of people seem to agree though that the "while" loop is one of the easiest. The difference between the "foreach" loop and the "while" loop is that the "foreach" loop is exclusively used for arrays while the "while" loop can be used in a number of different situations.

The "while" loop works on a very simple concept: while something evaluates to true, keep doing something else. Because we're working on the basis of true and false, we will need our comparison operators (discussed in lesson 7). If you can't quite remember, comparison operators compare values (or types) in two (or more) variables and return either "true" or "false".

Let's begin by looking at the syntax of the "while" loop:

while ( expression is true ) { do something }

the EASIEST way to show how the "while" loop works is to show you code right from the PHP documentation:

Code: [Select]
$i = 1;
while ($i <= 5) {
print "$i\n";
$i += 1;
}
?>

This is by far the greatest example code for the "while" loop because it shows you the very essence of why it exists. What we do first is declare a variable $i and give it an initial value of "1". The next few lines say exactly this: "while the variable $i is less than or equal to 10, print the variable then add 1 to it".

And here is what PHP will do (pardon the very detailed explanation, but it's important):
-set $i to 1
-begin loop, $i is less than or equal to 10 (true), so do everything inside the block
-print $i (1)
-increase $i by 1 (now $i is 2)
-continue loop, $i is less than or equal to 10 (true), so do everything inside the block
-print $i (2)
-increase $i by 1 (now $i is 3)
-continue loop, $i is less than or equal to 10 (true), so do everything inside the block
-print $i (3)
-increase $i by 1 (now $i is 4)
-continue loop, $i is less than or equal to 10 (true), so do everything inside the block
-print $i (4)
-increase $i by 1 (now $i is 5)
-continue loop, $i is less than or equal to 10 (true), so do everything inside the block
-print $i (5)
-increase $i by 1 (now $i is 6)
-stop loop, $i is now greater than 5 (false), don't do anything inside the block and move on

Here is the output you will see:

"1
2
3
4
5"

You have to be VERY careful with the "while" loop because you may accidentally throw your program into an infinite loop by writing and expression that always yields a true answer. PHP itself by default is set to stop a process which spans more than 30 seconds but if you accidentally get into an infinite loop on your web server, you will have some explaining to do to your administrator. Here is an example (although very stupid) of code which will yield an infinite loop:

Code: [Select]
$i = 1;
while ($i >= 1) {
print "$i\n";
$i += 1;
}
?>

This will print as many numbers (starting from 1) as it can before PHP decides to shut down the program by force.

To sum up the "while" loop: the "while" loop allows you to keep executing a chunk of code as long as some expression is true.

Lesson 10 - basics of user input

There are a number of ways to incorporate user input into your scripts. The single most used method of taking in user input is by using HTML forms. Let's take a very simple example of a HTML file with forms which point to a PHP script. I'm aware that some of you might not exactly be comfortable with HTML, if that's the case please read a few tutorials on the net about HTML.

Code: [Select]


Form 1:

Form 2:


The "get" method means that the form data is to be encoded by the browser into the URL and sent to the specific program. The "post" method means that the form data is to appear within a form data set and sent to the script. There is a general rule which states that you should use the "get" method when retrieving information and use the "post" method when sending information.

Let's say we filled in the above forms, filling in "form1" with "hi" and filling in "form2" with "bye". If were were to submit the above form with the "post" method, we would see "http://www.website.com/script.php" in the address bar. The information of the forms would be sent with the form data set (don't mind this too much, read more about it at http://www.w3.org/TR/REC-html40/interact/forms.html#form-data-set). But if we were to submit the information via the "get" method, you would see your address bar change to this: "http://www.website.com/script.php?forms1=hi&forms2=bye". The form information is encoded right inside the URL where you can see it instead of being hidden like the "post" method. Everything after the question mark ("?") is known as the query string. The query string holds all the user input someone submits via a form (or just manually in the URL). Every different form is separated by an ampersand ("&") or semicolon (";") and form names and values are separated by the equal sign ("=").

Now you might ask why this is important. Well first of all, URL caching. "get" methods are cached while "post" methods aren't cached by your browser. According to http://support.microsoft.com/default.aspx?scid=kb;EN-US;q208427, the "get" has a limit on the amount of information you can send by it. Because the "get" method uses the URL to send user input, it is limited by the maximum length a URL can be (2048 characters). The "post" method has no limitations on the amount of information you can send by it.

Because I don't want to get into the HTML of PHP scripting too much, I'm going to use the "get" method more often. This is because, I can show you examples without directly using HTML.

For example, we can access a URL like "http://www.website.com/script.php?forms1=hi&forms2=bye&forms3=something" and right from that we can get into the PHP of "script.php". Hope that made sense, next few lessons I'll go into detail with this stuff.

Lesson 11 - using user input

Sorry this one was a little late, I realized this was one of the things I was obligated to do, and I'll try to keep them coming in on time. There are a lot of things I didn't touch base on in this lesson. If any one of the developers want to add their comments, by all means go ahead. This particular topic is very hard to write about because there are so many "what ifs" involved.

So let's go back to last lesson's code example:

Code: [Select]


Form 1:

Form 2:


Let's now pretend I submitted that form with information via the "post" method filling in "form1" with "hi" and "form2" with "bye". To see this visually, I'll show you how it would look via the "get" method:

http://www.website.com/script.php?forms1=hi&forms2=bye

Remember that the only differences between the "post" and "get" methods are:
-"post" doesn't cache information, while "get" does
-the "get" method is limited in the amount of information you can send while the "post" method is not

So how do you access the information you submitted via HTML in the script (script.php)? Well amazingly, there are several ways to get the information. It's up to you to decide which method best suites you, and then go with that. When you submit a form to a script, a certain set of variables are automatically created for you.

The first way to access the information is via the "superglobals" PHP provides. "Superglobals" are variables that can be accessed anywhere in the script regardless of scope (we'll learn about this later when we get to functions). The "superglobals" are 9 special associated arrays which hold ALL the information you input into a script. Here they are:

$_SERVER - these are variables set by the server

$_GET - this is information you send via the "get" method into your script

$_POST - this is information you send via the "post" method into your script

$_COOKIE - this arrays holds all cookie information your computer sends to the script

$_FILES - when you upload files in PHP, they are held inside this array

$_ENV - the environmental variables

$_REQUEST - a combination of all user-input to your script

$_SESSION - much like cookies, these are session variables which hold information for you

I will be concentrating almost all the examples on the "post" and "get" methods because they are the easiest to follow. There are equivalent older versions of the above which are not "superglobals" and only exist in the global scope (again we'll get into this when we discuss functions). Here are the "superglobals" and their old deprecated counterparts (remember again that these are associated arrays):

$_SERVER - $HTTP_SERVER_VARS
$_GET - $HTTP_GET_VARS
$_POST - $HTTP_POST_VARS
$_COOKIE - $HTTP_COOKIE_VARS
$_FILES - $HTTP_POST_FILES
$_ENV - $HTTP_ENV_VARS
$_REQUEST - new, didn't exist before
$_SESSION - $HTTP_SESSION_VARS

By now you should be totally confused, and I completely understand if you are, because I haven't explained a thing about how to use these arrays. Let's take out "get" method example:

http://www.website.com/script.php?forms1=hi&forms2=bye

Here is how I would access the "form1" and "form2" information is submitted inside the script:

Code: [Select]
echo $_GET['form1'] . "\n"; //prints "hi"
echo $_GET['form2'] . "\n"; //prints "bye"
?>

We submitted our information via the "get" method, therefore the information will populate the $_GET array. Now if we submitted our information via the "post" method, then we could access they by replacing $_GET with $_POST. The information we submitted can also be found inside the $_REQUEST array, but it's recommended you don't use this array unless you don't know how your information is coming in (security reasons, nothing to concern yourselves with).

Let's try another basic example:

http://www.website.com/script.php?name1=Jeff&name2=Joseph (remember, this means you either typed this directly inside your address bar in your browser, or that you submitted forms with names "name1" and "name2" via HTML with the "get" method).

Code: [Select]
echo $_GET['name1'] . ' and ' . $_GET['name2'] . ' are too cool';
//will print "Jeff and Joseph are too cool"
?>

Again, if I submitted my information from a form via the "post" method, I'd simply replace $_GET with $_POST. Like I said, there are several ways to access information you send into your script. The "superglobals" are what you should be using all the time. The deprecated $HTTP_* variables you shouldn't be using anymore. There are also the global variables which I will explain now:

First to be able to use global variables, you have to have "register_globals" enabled in your php.ini file (if you don't but want it, ask your system admin to enable it). What these variables allow you to do is use short form versions of your input. So for example, if I submit a form via the "post" or "get" method called "form1", then I can use the $form1 variable to get its value. So for another example, if I submit a form named "something" via "post" or "get", and I want to retrieve its value in my script, I could use the $something variable to get it.

With these variables, there's always the question of "what about when I have several different sources of input, all with the same name?". For example, what if you set a cookie on the user's machine named "variable" and there is a session named "variable" and there is information coming into the form via the "post" method called "variable". Well then you would have $_COOKIE['variable'], $_SESSION['variable'], and $_POST['variable'] all set. But what about the $_REQUEST superglobal and the regular globals from (register_globals)?

Well in cases where information is coming in from multiple places with the same name, PHP allows you to set precedence on what is most important. In your php.ini file, there is a variable called "variables_order" under the "data handling" header. By default this is what it looks like:

Code: [Select]
; This directive describes the order in which PHP registers GET, POST, Cookie,
; Environment and Built-in variables (G, P, C, E & S respectively, often
; referred to as EGPCS or GPC). Registration is done from left to right, newer
; values override older values.
variables_order = "EGPCS"

The explanation on that is good enough. That means that with $_COOKIE['variable'], $_SESSION['variable'], and $_POST['variable'] all set, $variable will have the value of the cookie variable in it.

Lesson 12 - using functions

I've explained what a function is in lesson 3; now let me tell you how functions work from the PHP point of view. You use functions when you have code that repeats. Anytime you find yourself repeating a fair chunk of code, you can change it to a function saving yourself a lot of time typing, and a lot of space for the code.

PHP is built up of several functions. For example, this function allows you to convert a string to upper case:

Code: [Select]
$string = 'this is a phrase';
$string = strtoupper($string);
echo $string; //prints "THIS IS A PHRASE";

strtoupper() is the function. What it does is convert each character in my string to upper case characters. This function saves you space because it automatically converts each character in the string to upper case for you. If we look in the PHP documentation, this is what strtoupper() (http://ca3.php.net/manual/en/function.strtoupper.php) will tell us:

-The first line gives you the name of the function - "strtoupper"
-The second line tells us what versions of PHP handle this function - "(PHP 3, PHP 4)"
-The third line gives a very basic definition of what the function does - "strtoupper -- Make a string uppercase"
-The fourth line (and everything after) explains how the function works and gives definitions - "string strtoupper (string string)".

Let's take a look at how the function works:

string strtoupper (string string)

This says that when you use the "strtoupper" function and feed it a string, it will return a new string. In other words: "string = strtoupper(string)". You can read the PHP documentation on this function if you need examples.

The information you feed into a function are called "arguments". The information a function can take are called "parameters". These two words are sometimes used interchangeably. When you define a function you define its parameters, but when you use a function, you give those parameters actual arguments.

Another very common function is the sort() function. What this does is sort an array for you. Let's look at the PHP documentation to see how to use this particular function (http://ca3.php.net/manual/en/function.sort.php).

void sort ( array array [, int sort_flags])

This function does not return any value (void), so you can't use assignment with this function. In other words: "sort(array,int)". The sort function takes an array as the first argument, and takes an optional second argument (that's what the [ and ] brackets mean, optional) which is an integer. Reading the documentation a little more, we discover that the first argument is the array we want to sort, and the second optional argument allows us to sort the array in a particular way depending on the type of information we have in the array. Let's look at a code example:

Code: [Select]
$array = array('b','a','q','z','y','a','c'); //let's define an array we want to sort
sort($array); //let's feed the array (via an argument) to the sort() function, and leave the optional argument blank
foreach ($array as $element) { echo "$element\n"; } //let's print out the array

That will print:

"a
a
b
c
q
y
z"

Read the PHP documentation and look for functions that might interest you. Functions are named like actions (not quite verbs, but close). You can find the functions (organized by type) at http://www.php.net/manual/en/funcref.php. You can also find a full list of the functions at http://www.php.net/quickref.php. To sum up everything above, you feed information to a function, it does a few things with the information you feed it, and it gives you new information back.

Lesson 13 - creating custom functions

By now, you should have yourself familiarized with the built-in PHP functions, if you don't, please go back and review them. Again, the functions are located at http://www.php.net/quickref.php and you are encouraged to read through them and get yourself familiar with the many different actions you can perform with them.

One of the many functions in the PHP documentation is array_sum(). array_sum()'s documentation can be found at http://www.php.net/manual/en/function.array-sum.php. What does array_sum() do? It simply adds up all the number types in an array and returns the sum. You should know how to use this function (from reading the documentation):

Code: [Select]
$array = array(1,5.5,2.0,3,6,1);
echo array_sum($array); //prints "18.5"
?>

This is a clear example of what a function is there to do. This function does a specific task and it saves us from having to repeat code (possibly from summing up several arrays). Our task for this lesson is the create a NEW function which performs the exact same function as array_sum(). This will help us learn how to implement our own custom functions and also give us a better understanding of why we create functions.

The basic syntax of a function is the following:

function function_name($parameter_1,$parameter_2...$parameter_n) {
//do something with the parameters
//create a new variable ($variable)
return $variable
}

In case you're curious, this is what return does: When you do "$variable = array_sum($array)", array_sum itself uses the "return" statement which returns a value which in turn you assign to $variable.

Because we want to keep this as simple as possible, we're going to go about making our function with the assumption that the contents of the array will always only be number types. The first thing we want to do is create the body of our function. What does this mean? This means that if we had a variable (or variables), how would we go about doing the job we want to do?

So let's say we have our variable $array (of array type), and it contains numbers. How do we go about adding all the numbers?

Code: [Select]
$variable = 0; //create our new variable to store the sum
foreach ($array as $element) { //pretend as if you already have $array
$variable += $element; //add the element to the variable holding the sum
}

We're already half way done; we've created the body of our function. Let's give our function a name now. In PHP, you cannot name functions which are built into PHP, or else you'll get an error stating you can redeclare the function. Since the function we're duplicating is called array_sum(), we'll call our function array_sum_copy(). What variable(s) does our function need as input to do its job? Well, above, we created the body of our code under the impression that an array ($array) was declared, so that is what we'll need as input. Finally, what output does our function return? Well, we know that the body of our function stores the sum of the array elements inside $variable, so that's what we'll want to return to the user of the function (using the "return" statement).

Now all we have to do is put our function together:

Code: [Select]
function array_sum_copy($array) {
$variable = 0;
foreach ($array as $element) { //pretend as if you already have $array
$variable += $element;
}
return $variable;
}

Let's go back and once again look at what we did. We selected a name for our function. We found out what variables our function will need to work (the parameters). We created the body of our function and used all the parameters of the function. Finally we figured out what output we want to return and we used the "return" statement to return it.

And this is how it would look if we used it:

Code: [Select]

$array = array(1,5.5,2.0,3,6,1);
echo array_sum_copy($array); //prints "18.5"

function array_sum_copy($array) {
$variable = 0;
foreach ($array as $element) { //pretend as if you already have $array
$variable += $element;
}
return $variable;
}

?>

I will be doing one more of these in a few lessons, but I want to just note on a few things. First, you can create a function that has SEVERAL parameters. Second, a function can return SEVERAL values (this will be demonstrated later). Finally, variables declared in a function will only exist in that function. For example, we declared $variable to hold the sum of the array elements, but $variable will only exist within the block it was declared, nowhere else (unless otherwise stated). This is where we get into scope, and I will be explaining how scope works in PHP in the next lesson.

Rate this Article:

Be the first to rate me.

  • php basics

     | By terninator | in General

    Lesson 01 - Installing a Server Lesson 02 - PHP Basics Lesson 03 - Variable/array/function definitions Lesson 04 - ...

  • php basics (part III)

     | By terninator | in General

    Lesson 14 - Variable scope and global declaration Lesson 15 - Variable referencing Lesson 16 - More function exampl...


* You must be logged in order to leave comments, please login or join us.

Comments

No comments yet.



Bookmark and Share
Sign up for our email newsletter
Name:
Email: