PHP Fundamentals


  1. Introduction PHP is a real programming language. I think that from the beginning, when its acronym stood for Personal Home Page, some might've thought less of the language's capabilities. In this course, I hope to dispel any such thoughts by covering many of the ins and outs of this robust and flexible programming language.

  2. Intended Audience You are probably wondering if this course is for you. This course is targeted to those developers or individuals who are new to PHP. This course is basically focused on getting you up to speed with the syntax and the nuances of the PHP programming language. Now as you contemplate on whether you will continue this course, I do encourage you to check out the history of PHP in the next clip.

  3. History of PHP In 1994, a guy by the name of Rasmus Lerdorf wanted to track how many people were visiting his online resume. He created a handful of CGI scripts written in the C programming language to accomplish this task. In June of 1995, Rasmus released his scripts to the public under the name of PHP Tools version 1.0 where PHP at this time stood for Personal Home Page. These scripts not only included being able to log pages, they also had the ability to password-protect pages and create and display forms. A year later in April, the second version of PHP was released. This version had a new name. It was PHP/FI. The FI stood for Forms Interpreter. Some of the new features in this version included conditional statements. This was in response to the public wanting the ability to hide and show blocks of HTML code. Another new feature was the ability to access databases, and the term scripting language was also used for the first time with the release of this version. PHP 3.0 was released in June of 1998. This time Rasmus had some help from Zeev Suraski and Andi Gutmans. They rewrote the underlying parsing engine for PHP. This version also supported all major operating systems, and it supported more databases than the 2.0 version. One of the most notable changes in PHP 3.0 was the new name. Originally, PHP stood for Personal Home Page. In this new version, PHP stands for PHP Hypertext Preprocessor. This is known as a recursive acronym. In a recursive acronym, one of the initials is the actual name of the product, in this case PHP. Sometimes people might refer to this as a recursive backronym. In this sense, a recursive backronym means that you already have the initials of a product, and you go back and put new meaning to each of those initials, in this case PHP Hypertext Preprocessor. In the course documents, I have provided the link to the email discussion discussing the renaming of PHP. In May of 2000, PHP 4 was released. Zeev and Andi rewrote the core engine for PHP, and they renamed it Zend Engine. There were a few minor releases between PHP 4 and PHP 5. PHP 5 was released in July of 2004, and the second version of the Zend Engine was also released. The next major version of PHP was going to be PHP 6, but there was a problem. The big push with PHP 6 was Unicode. The problem was there wasn't enough developer support for the new Unicode platform. This caused an issue, so PHP 6 never fully got off the ground. What has happened is the non-Unicode features from PHP 6 have been backported into PHP 5. But what about PHP 6? Since PHP 6 was technically there, whatever there means, it has been bypassed for a major release. Instead of version 6, we are now working with version 7 of PHP. At the release of this course, the current version of PHP is 7.0.1, which was released in December of 2015.

  4. What's Possible? So what's possible with PHP? Its primary use is for creating websites, but some individuals are unaware that PHP can also be used as a command line scripting language similar to Python and Perl.

  5. Sample Programs We've been talking a lot about PHP and what it can do. Let's actually look at some code. I have two simple programs that I'd like to show to you. The first will be a simple script program, and the second will be a simple web script, which will include HTML. Here's our first PHP script. At the very beginning, we have what is called the opening PHP tag. Following the opening PHP tag, we declare a variable named message. You'll notice we don't declare the type of variable we have created. That is because PHP is a weakly typed language. We just set the variable and then the contents that we want to put in it. After declaring our variable, we now want to print it out, and we print out our message variable using the echo keyword. Now if you wanted to, you could substitute echo with print. Throughout the course, I'll be touching on the differences between echo and print, but for now we're just going to stick with echo. After our code, you'll notice we have a closing PHP tag. Not all PHP scripts need a closing PHP tag. The closing PHP tag is only needed if you're going to be dealing with HMTL, which interesting enough, our next PHP script has HMTL. Here is a simple PHP web script. The beginning should look familiar. We have our opening PHP tag. We're setting two different variables. Again, we don't have to declare the type because PHP is a weakly typed language. We have a closing PHP tag. Now this is important because after it we are actually having HTML rendered to the screen. If you don't have the closing PHP tag, an error will be thrown. Now we have our two variables, but we need to actually use them in our HTML code. In order to use our variables, we need to be able to insert them and print them out. Let's skip down to the second variable message in our H1 HTML tag. It has the standard opening and closing of the PHP tag, and then we're actually printing out the message using echo. This is a typical print statement inside of HTML code. Now let's look at the title tag. Inside of our title tag we are printing the variable title. Now the opening and closing PHP tags look a little different. Instead of having PHP and the echo, we have substituted that out with the equal sign. This is the shorthand version of printing out a variable inside of HTML code. You might be asking yourself well which way is the better way to print out your variables? And the answer is it doesn't matter. The only thing that matters is consistency. Don't mix and match. It makes for much more readable code.

  6. Running PHP Scripts in Netbeans For the purpose of this course, we're going to use NetBeans as our IDE. The beauty about NetBeans is that we can run a PHP file and have the output displayed right here in our window. I'm going to open up our sample file here. You'll notice my PHP tag does not have a closing. Since we are not dealing with HMTL, there's no need to have a closing PHP tag. Before we run our script, we need to make sure our environment is set up correctly. We just need to select the Run menu, and right here off of the Set Project Configuration, we need to select Customize. There are two things that you need to set in order to run a script inside of NetBeans. First we need to set the Run As. You should select the one that says Script (run in command line). And then we also need to set the PHP Interpreter. In this case, this is the path in a Linux environment of where my PHP program is. For Windows, you need to navigate using this Browse button to your PHP.exe file. Now in order to run this file and have the output displayed here inside, we just need to go up to the Run menu and select Run File. Note that it also has a shortcut of Shift+F6. I'm going to run it, and the output window appears, and here's the result of our PHP script. I'm going to close this and just use the shortcut keys Shift+F6, and we get the same result. Now no matter how many files that we have here, we'll be able to execute each of them inside of NetBeans. This is going to save us a lot of time instead of having to go into a terminal or a command prompt to execute our PHP scripts. Now NetBeans is available on the Windows, Linux, and Mac operating systems.

  7. Reserved Keywords As with any language, there are reserved keywords. Here is a list of some of the keywords that are reserved in PHP. We will learn this section of keywords throughout the rest of the course. PHP also has reserved variables. Most of the time these variables are used when dealing with forms. We will be using some of these variables later in the course when we cover the processing of PHP forms.

  8. Course Outline So what will you learn in this course? I'm going to go over the course outline. In the next module, we're going to learn about the general types in PHP. This includes floating points, constants. We are also going to cover comments and case sensitivity. In our String module, we're going to go over how to work with strings in PHP. This includes going over a handful of built-in functions that PHP has for string manipulation. Our following module will be about arrays. I hope I can convey how flexible and powerful the arrays are in PHP. Then we're going to tackle the functions in PHP. We'll talk about passing arguments and returning values. In the Control Structure module, we'll cover a couple of operators, but our main focus will be on how to include files in our PHP program. Next we'll tackle classes and objects, and follow that with web programming and how to take our PHP code and actually work with HMTL code to produce a dynamic website. Our last module will be about databases. This module will focus on the MySQL database and the connectivity it has built-in. So that's it. That's our course outline in a nutshell. Let's head over to module 2 and start learning about our general types.

  9. General Types Overview This is module 2, and in this module we're going to cover the General Types. What does that exactly mean? It means we're going to be covering some of the basics of the PHP programming language. And when I mean basics, I mean basics. We're first going to cover the comments and case sensitivity. Then we're going to go over some of the variables. These variables that we'll cover in this module include integers, Boolean, decimals, and constants. Using built-in functions, we'll then be able to determine those different variable types. As a side note, in this module we will be using functions, though we have not covered them yet. The functions that are utilized in this module are pretty basic. They shouldn't cause you too much of a headache as you go through the demos.

  10. Basics - Comments, CaseSesitivity I'm going to cover a few basics of the PHP programming language, in particular the comments and the case sensitivity. PHP has a few different ways that you comment out code or add comments within your code. The first way is probably the most standard way in almost all high-level programming languages, which is the two forward slashes. This is based on the C++ programming language style of comment. The next style of comment is the C-style comment block. This is the forward slash with the asterisk, closing off with the asterisk and another forward slash. PHP has a third way of adding comments to your code, and that is using the shell style comment, which is the hashtag or pound or sharp, however you want to say it. This style of comment is the exact same as if you were using two forward slashes. Even though there are multiple ways to add comments to your code, it is ideal to have some sort of consistency on how you use which style of comments. Case sensitivity in PHP is fairly straightforward. All variables in PHP are case sensitive. This means that each of the variables that are declared here are different. Notice the second variable has a capital C in Case whereas the first does not. This indicates that these two variables are separate and hold two different values. PHP classes are not case sensitive. So what does that mean for you? That means you can randomly capitalize any class declaration, and it will still point to the same class that you want. Each of the class declarations in this example will not throw an error and refer to the same class company. PHP functions are also not case sensitive. In the example here, I have called the exact same function three different times with three different case scenarios. They all refer to the exact same function and will not throw an error.

  11. Type - Integer (Demo) Now we get to do some actual coding. I've already created a file called integers.php. In this clip, we're going to go over the different types of integers that PHP allows. All variables in PHP start with the dollar sign and then your variable name. Now in order to print this out so we can see the value of our variable and the type of variable it is, we're going to use a built-in PHP function called var_dump, and inside there all we need to do is pass in our variable name. Now when we run this by using Shift+F6, you'll see at the bottom it not only displays our value of our variable, but it also tells us what type our variable is. Now as with all integers, sometimes we need them to be negative. PHP allows for you to put the negative right in front of it, and if we hit Shift+F6, we can see that our variable is holding that negative value. Not only does PHP do integers just like other programming languages, PHP can also handle octal numbers. So if I were to come down here, I'm going to make a new variable and call it octNum, and I'm going to give it an octal number. All octal numbers start with a 0, so in this case I'm just going to give it an octal number of 01234. Now we're going to go look and see what happens when we dump the variable, and the output is an integer with a value of 668. Did you also know that PHP can handle hex numbers? Well PHP can handle those hex numbers. I'm going to make a new variable here, call it hexNum, and now for our value. The hex value needs to start with 0x. Then it needs to be followed by any combination of numbers 0-9 and A-F. For our hex number, I'm just going to give it a value of ABC. Let's go ahead and output our value, hexNum, and we'll run our program. Here at the bottom the hex number of ABC is converted to an integer of 2748. That's pretty cool. Now did you know PHP can also handle binary numbers? Well PHP can handle those binary numbers. I'm going to write a new variable here, we'll have our binary number, and to signify that your value is going to be a binary number you preface it with a 0 and then a lowercase B. Then you follow it by your 0s and 1s. Most of us who program are familiar with some of the lower binary numbers. In this case, if I were to type 1000, the result should be 8. Let's go ahead and see if we're correct. We are. Now each of our variables here are kind of on the small side. PHP can handle very large variables. Depending on your platform, an integer in PHP for a 32-bit signed value can be about a little bit over 2 billion. Now if you're on a 64-bit platform, it actually can go up to 9 to the 18th power. That is a large number. Now for those of you who are interested, PHP does not support unsigned integers. So what happens if an integer goes larger than the value it's allowed? Well PHP automatically converts it to a float. In our next clip, that's what we'll be learning about, our floating points, or as some like to refer to them, decimals.

  12. Type - Decimal/Floating Point (Demo) Another variable type is called floating points. Other programming languages probably refer to it either as decimals, floats, doubles, real numbers, but for now we're just going to call them floating points. We're going to make a variable just like we've done before, $, and then we just give it a name. And in this case we're just going to give a simple decimal, and then we'll just dump this out and see what it says. So I'm going to hit Shift+F6. Here we have our variable, and it tells us what kind it is, float, and then the value that our variable is holding. Now floating points are pretty easy in PHP, but did you know that you can also use scientific notation? I'm going to create a new variable, and I'm going to give it a scientific value now. So I'm going to start out with a floating point, and now in order to make this a scientific number, I follow my number with the letter E. Now this can be lowercase or uppercase. I prefer the uppercase. It makes it look more scientific. So now I'm going to make this to the power of 4, and let's go ahead and see what our variable is holding. I'm going to hit Shift+F6, and if we look down here, it's telling us that we are using a floating point, but the value is an integer. I bet you are wondering what about having it to the negative power? Well I do believe PHP can deliver. So I'm going to use the exact same variable; I'm just going to override it. In this case, I'm using an integer for my initial value. I'm going to use the capital E, and then I just need to put in a negative power. I'm going to hit Shift+F6. Down below you'll see that our variable type is a float, and here's the value that it's holding. Now having the ability to do scientific notation is pretty cool. Now if you'll ever use it, it's to be determined. I want to point your attention to this small little triangle here inside of NetBeans. If you hover over it, it signifies that I have two of the exact same variable and that one is being overwritten. It's absolutely correct. I named two variables scientific. Now there's nothing wrong with that. NetBeans is just pointing out a warning, kind of like a hint letting you know that you might want to look into this situation. When you start getting more complex code, those little warning hints are actually kind of valuable. That's it for floating points or real numbers or doubles or decimals.

  13. Type - Boolean (Demo) Now it's time to talk about Booleans, or Booleans, however you would like to say it. So I have a new file here, and I'm just going to put our var_dump at the bottom so we're ready to go. Now I just need to make a new variable. Like with all of our variables, it starts out with a dollar sign and then some name, and in this case I'm going to give it a value of true. You'll notice there are no quotation marks around our value. Now I just need to go down here and add it to our var_dump, hit Shift+F6, and if you look down here in our output window, you'll see that the type is bool, and the value is showing as true. Now if I were to change our variable to false and hit Shift+F6, you'll see that now it is appearing as false down here in our output window. Booleans are very easy to use in PHP, but what might also be helpful is that you can convert any value to a Boolean. I'm going to make a new variable and demonstrate this. So here's our new variable, and I'm going to set it to a number. Now if I do a var_dump on this, I'm just going to get the exact value that I put in. So we need to convert this to a Boolean. In order to do that, in front of the variable I just put in parentheses, bool. Now If I run this, Shift+F6, since this variable had a value, the conversion to a Boolean became true. Now if I were to have this as an empty value, so let's change it to a string and just have an empty string, and if I run Shift+F6, I come down here in our output, it's still declaring that it's a Boolean value, but now our value is false. The same can be said with an empty array or if the value is 0. Let's do a value of 0 since we haven't gone over arrays yet. And there's our output, and you can see it's been converted to a false. And for one last test, because they're so much fun, we're going to actually put a value in a string variable. And let's run this. As we look down here at the output window, you'll see that it has converted it to true. Booleans in PHP are very straightforward and very easy to use, as with other high-level programming languages.

  14. Type - Constant (Demo) The next type of variable that we're going to cover is constants. And it's not actually a variable; it's a constant. And to create a constant in PHP, you need to define it. So in order to define our constant, we actually type the word define. Define acts as a function call where it takes two parameters. So our first parameter, a string value, will be the name of our constant. I'm just going to type in NEW_CONSTANT. Now naming conventions in PHP, they dictate that all constants are uppercase, and any of the words are separated with an underscore. Our second parameter is the value that we'd like to give that constant. So in this case we're going to just give it a string value, make sure we close our parentheses. Now since we know this is a constant, we don't need to do a var_dump on it, so instead we're just going to echo out our constant, and in this case we type our constant just like we defined it, but without the quotation marks. So we say NEW_CONSTANT, all uppercase, and in order to run this we hit Shift+F6, and down below in our output window you'll see our constant has been printed out. Now the beauty about constants is that they are global variables. That means that you can access them anywhere within your PHP script no matter what, inside functions, inside classes. Wherever you need to access this, you can access it. We will cover more about variable scope when we cover functions, but just know that constants can be accessed anywhere.

  15. Determine Variable Types (Demo) Now it's great that we can store any type of value inside of our variables, but what happens when we actually need to know what kind of a value we have? Well PHP has a bunch of built-in functions that we can use. I'm going to paste a variable of each type here in my new file. Here are my variables. I have a constant defined here up at the top, an integer, a string, a Boolean, and a float. Now one-by-one we'll go ahead and check these off of our list of how to find out what's inside their value. If we wanted to find out if intVar was really an integer, we would use the function is_int. Now if I run this, nothing will happen because we're not printing anything out. Now the is_int is returning a value, 1 if it's a success, and nothing if it's false. So we can either capture this in an if statement, or we can just print it out directly. For the sake of this example, we're just going to go ahead and print it out. So I'm going to use echo, and again we're checking to see if the intVar variable is actually an integer. So I'm going to hit Shift+F6, and in our output window we have a 1. That indicates that it is an integer. Now if I were to exchange this variable for a different one, let's go ahead and put in the float variable and run this, Shift+F6, you'll notice nothing was printed out. That means it's false. So 1 is equal to true, and nothing is equal to false. It makes for a very easy if statement because 1 in an if statement is true. Now in order to test if a variable is a string, we use is_string, and I can put in the stringVar. And if I run this, you'll see the output is a 1 indicating it is true. Now if I switch this to be an integer and run it again, nothing is outputted. When it's a 1, it's true, and when it's nothing, it's false. I'm going to go through the rest of these pretty quickly, so echo for Boolean is_bool, and then we put in the value that we want to check. We'll run it. It's a 1. And our last test of our variables is is_float. We'll run it, and we get a 1. You'll notice they print on the exact same line. I didn't comment this out, so there's a 1 and a 1. If I were to comment this out and actually run it again, you'll just see the single 1. The last thing we need to be able to check is if something is a constant. Not necessarily that it's a constant; we need to see if the constant has been defined. So now we know we have a constant called CHECK_CONSTANT. So just like we define a constant, we're going to check to see if it's defined with a D at the end, so we type in defined. This function takes one parameter, and it's the actual constant name. We need to pass it in as a string. Just like when we define a constant, when we check to see if it's defined, we're using quote marks. Here I'm going to type in my constant name. I close the parenthesis and make sure I put my semicolon. Now there's one last thing that we need to add to our line of code. We need to be able to print out what this is returning. So I'll type in echo, and now we can go ahead and run this program. And it's returning a 1 indicating that our constant CHECK_CONSTANT has been defined. Now if I give it a false name, so let's say I'll just change this to NEW, and I run it, it returns nothing. So we have 1 means it's been defined, and nothing means that it has not been defined. As with any programming language, you just need to get familiar with some of the built-in functions that the language has to offer.

  16. Summary In this module, we covered the general types in PHP. That entails the comments, case sensitivity, integers, decimals, Booleans, constants, and the ability to determine what type of a variable you're using. In the next module, we will cover all aspects of creating and using functions.

  17. Functions Overview This module is going to be all about Functions. In other programming language, functions is referred to as methods, but since we're working with PHP, we're just going to stick to the word functions. In this module, we're going to cover creating and calling a function, parameter passing, including default parameters, and definitely we'll touch on returning values from our functions, and variable functions, which is a really cool feature of PHP. And last but not least, we're going to cover variable scope inside of our function and within our PHP script.

  18. What Is a Function? So what is a function? A function is a block of code that performs a specific task. The reason why we create this block of code is so that we can reuse it throughout our PHP program. In our last module, in the clip called Determine Types, we actually used function calls. We're now going to see what a typical function call looks like. Here's the general syntax of a function. First we start out by typing the actual word function. Now we need to remember that PHP is a weakly typed language, so we do not need to declare the type of a function that we're creating. We just need to type the word function, and then we follow it with our function's name. After our function's name, we use open and close parenthesis. Now in this example I'm showing that we can pass in parameter variables, and we'll cover that later in the module, but for now just know that our parentheses are needed, and then we would include any parameters that we want to pass into our function. After our closing parenthesis, we then use a pair of curly brackets or curly braces or squiggly parentheses, however you want to say it. And that's it. That is the general syntax of a function. Now inside of those curly brackets, that is where we will put our block of code for the function to execute. So what are we waiting for? Let's go and create our first function.

  19. Creating a Function (Demo) So we know what a function is. It's a block of code that we can reuse throughout our program. Now we're going to learn how to create a function. Each function has to start with the keyword function. Now we don't need to declare what type of a function it is because remember PHP is a weakly typed language, so following the function keyword we just need to give our function a name. Following the function name, we just type in an open and close parenthesis. Following the open and close parenthesis, we then type in our opening and closing curly brackets. And that's it. We've created a function, but this function is going to do nothing when we call it. We need to put in some type of code inside of the function for the function to execute. For simplicity, we're going to actually print out a statement inside of this function. I'll type echo, and then have it print a string value. Now our function is complete because not only have we created it, we have it actually executing some type of code inside of the curly brackets. Let's go to the next clip, and we'll learn how to call our function.

  20. Calling a Function (Demo) So here I have a function I've already created. Note the \n. This allows each of the strings to be printed to their own individual line. Now if you remember from the previous module, in order to call a function, you just call it by its name, and then in this case we'll have an open and close parenthesis. Now let's go ahead and run this script. Remember Shift+F6, and you'll see the output down below. Now when you're calling a function, it actually does not matter whether you put the call before the function or after the function inside of the script. So let's go ahead and copy this call, and put it before the function. And let's go ahead and execute that. Notice that it still prints out the contents of the function that we called. Calling a function is relatively easy, but it does get a bit more complex when we start passing in parameters, which we'll learn about in the next clip.

  21. Passing Parameters (Demo) So I have a function here, and you'll notice something a little bit different than the other functions that we've used. Inside of the open and close parenthesis, you'll see there's a variable name. This variable name allows us to accept a value that is being passed into our function. In order to pass in a value, we call our function, and inside of the function call parentheses we put in the value that we'd like to pass in. The best way to understand how this works is to actually see it in action, so let's go ahead and type our function call down here, and inside of the parentheses we're actually going to include a value that we want to show up inside of our function code. So I'm going to pass in an authorName, and let's go ahead and run this program. You'll notice that the authorName has been printed out with the correct value that we passed in. We passed in our value directly from our function call, but what if we had a variable that we wanted to pass in? It works the exact same way. So instead of putting the actual string value inside of our function call, I'm going to create a variable, and then I'm going to pass that variable into our function. So I'm going to type out authorName as my variable and give it a string value, and then I'm going to take that variable and put it inside of my function call just like we did with the string value. You'll notice it works the exact same way. I'm going to hit Shift+F6, and the output is the exact same. Now what if I wanted to pass in more than one variable? That's easy. You separate each variable that you would like to pass in with a comma. Now passing in a second variable in our function is going to alter what our function does, so I'm going to change the name of our function, and now I'm going to allow it to accept another variable that's passed into it. Now we have the variable name, but we're not actually doing anything inside of our function with it, so let's go ahead and print this variable out as well. Now the last thing we need to do is call our new function with the two parameters that it's asking for. So we already have the first parameter set as a variable. Now our second parameter we can pass in as a straight value inside of the function call, or we can create a variable and pass it in that way. Since the other value is already set as a variable, let's create a new variable and pass that value in via a variable name. Okay, now we have our variable, and we're passing it in, so let's go ahead and run our script. In the output window, it's working exactly as we wanted. Sometimes you'll have a function that takes a certain amount of parameters, but we don't necessarily have the actual values for each of those parameters. In this case, we want to be able to have some default parameters set up. In the next clip, we're going to cover default parameters and how to have default values already set inside of our function.

  22. Default Parameters (Demo) I have the function here from our previous clip. You'll notice I've changed the variable names inside of the function. This should make it easier to understand parameter passing and the use of default parameters. In order to change one of these parameters to be a default parameter, all I have to do is add an equal sign to the variable name, and then I can give it any default value that I'd like, and this can be any of the general types. And in this case I'm going to use an integer for the year. So now I've set up our function to accept two parameters, one with the default value. Now we call this function the exact same way as we called our other functions where we're just passing in regular values. Let's first call our function with the two variables being passed in. So I'm going to type out booksByAuthorYear and pass in my two variables that I have already set. Now when we run this, Shift+F6, you'll see the values coming through. Notice the year value. It's 1920. That's the value that we've passed in. So our function is still behaving just like normal, but what happens when we take away the year value in our function call? Typically a warning error will be thrown, but if we have a default parameter set, no error will be thrown, and the function will execute just like normal. But what about the year variable you ask? Well the year will be set to the default value that we gave it inside of our function. The best way to understand this is if we actually run the example. Now when I execute this, you'll see the year value will not be 1920 as our declared variable is, but the year should be 1910, our default parameter value. I'm going to hit Shift+F6, and you'll notice the year is coming in as 1910, our default parameter value. You might be wondering is that all there is to default parameter passing? And the answer is yes. That's basically it. There is one thing that you do need to remember, that all default parameters need to be at the end of the function declaration, all required parameters need to be at the beginning of the function declaration. That's not too hard to remember, and if you forget, don't worry, PHP will remind you by throwing an error.

  23. Returning Values (Demo) Up until now, we have been printing out what's inside of our function, but for the most part we won't want to print out anything inside of our function. We'll want to return a value. And in order to return a value, we need to tell the function that we want to return a specific value. So here I have my function, my variables, and my function call from the previous clip. I'm going to create a new function, and we're going to return a value from that function. So to create a new function, I'll start out with the keyword function, and this time our name is going to be getAuthor. I'm not going to pass in any parameters, so I just need any empty set of parentheses, and then make sure we use our squiggly brackets or curly braces. Now in order to return a value, we actually type the word return, and then we return the value that the function should be returning. In this case we're going to return a string value, but remember the return type can be any of the general types. Our function is now ready; we just need to call it. Since this function is returning a value, if I call it without saving it to a variable, it will actually do nothing, so we need to capture our return value inside of a variable. In this case, I'm going to replace the authorName with our function call. So our function call will now return the value into the authorName variable. I just need to type getAuthor, open and close parenthesis, and now I just need to execute this script. Notice our authorName is coming in as Charles Dickens. We got that value from our getAuthor function. We returned the value inside of that function and saved it inside of a variable. Returning values is extremely easy. Just remember the keyword return.

  24. Variable Functions (Demo) PHP has a cool feature where you can call a function by using a variable name. This might sound a little bit tricky, so it's best to show you exactly what I mean. I already have my function defined, so now I need to put the name of my function as a string value stored in a variable. So here I'm going to just write a quick variable, and I'm going to set it to my function name. In this case, it's getAuthor. Note that my string representation of the function has no parentheses. I'm literally just typing the name of the function without the parentheses. No parentheses. Now in order to call my function by variable name, I just need to type out the variable name, and then at the end I just put the two parentheses and my semicolon. Now let's go ahead and run this. Our function was called, and it printed out Charles Dickens. That is pretty cool. Variable functions can open up a whole new set of possibilities inside of your PHP script.

  25. Variable Scope (Demo) Now we're going to talk about variable scope. I have some code here. I first have a variable, and then I have a function, and inside my function I have another variable, which happens to have the same name as the variable that is outside of my function. Now we're going to print the variable name, so I'm just going to type in echo and then the variable name. And go ahead and run this, and you'll see that the name that is printed out is William Shakespeare. This is to be expected because I have not run the function at all. Let's run the function, and we're going to run it right before the echo statement, so I'm just going to type in setAuthorName. I'm going to go ahead and run this script. You'll notice that the authorName variable is still printing out William Shakespeare. This is because the function has its own variable scope. Since variables that are set inside of a function are only available inside of that function, when we print this variable out, we get the outside variable name, which is William Shakespeare. Think of the function as a box. We can't see inside of the box to see what's going on, and unless something is returned to the outside of the box we'll never know what's going on inside, and we'll never have access to any of the variables or other items of code inside of that box. We do, however, have access to the variables outside of the box. So when we printed the authorName variable, we printed out William Shakespeare, which was set outside of the box, or function in this case, which we do have access to. The variable scope concept might have to settle in your mind for a bit. While it does, let's go on and talk about global variables.

  26. Global Variables (Demo) We have the code from our variable scope. We still have our authorName both inside and outside of function, we're also running the function, and we're printing out the authorName variable. Now when this runs, it will print out William Shakespeare. Let's go ahead and run it just so we know for sure. Now what we want to do is we want to make that authorName global. That means wherever it is we want it to change values when it's set, whether it's inside the function or outside of the function. In order to this, we need to actually go inside of the function and write a new line of code. The new line of code will start out with the word global. This is a reserved keyword in PHP. After the global keyword, we then type the variable name that we would like to be global. In this case, we want it to be authorName. That one line of code will make the authorName variable global. Let's go ahead and run this. Here is our result. The authorName now holds the value of Charles Dickens. This is exactly what we had hoped for by using the global keyword. There is a caveat to using the global keyword in front of a variable. It only works if you're inside of a function. If we use the global keyword on the variable outside of the function, it just makes it global for everything outside of the function, which it already is. We want it to be global inside and outside of the function. In this case, that global keyword needs to be inside of the function. This method of making a variable global is the same when we start working with classes, which we will cover in a later module.

  27. Summary In this module, we learned all about functions. We defined what a function is, we created a function, we called a function, we passed parameters to a function, we used default parameters on a function, we returned values, we even learned about variable functions, and are they not pretty cool? I thought so. And lastly, we learned about variable scope.

  28. Strings Overview Strings are an integral part of the PHP programming language. It is almost inevitable that in any of your PHP scripts you will utilize strings. With that being said, in this module we're going to cover the basic string creation. We'll go over what we've previously learned in the other modules and add on to that. Up until now we've been using the echo keyword to print out any of our variables. In this module, we will demonstrate the print function and when it's applicable to use it. Then we'll move on to string functions. PHP has a ton of built-in string functions. And when I say a ton, I mean close to a hundred different string functions that we could use. To add a sense of drama, here is a list of all of the string functions that PHP has to offer. And if you're counting, that's a total of 98 string functions. Now those functions that have been highlighted in this list will be taught in this module. Now that you've seen all the functions, let's get started on basic string creation.

  29. Single Quoted Strings (Demo) Up until this module, we've been using double quotes to create our string variables. In this clip, we're going to cover creating string variables using single quotes. I already have a variable with a string value using single quotes. When I run this, you'll see that it comes out with the exact same printed statement that we would see with double quotes. What if we wanted to add a variable to our string? Let's go ahead and do that that and see what happens. So I'm going to start out with a variable, and we're going to call this variable currency, and then I'm just going to give this a value of penny. Since this clip is dealing with single quotes, we'll use a single quote around our value, though even if you used a double quote for the value of our currency variable, it would still return the same result. Let's go ahead and replace the word penny inside of our string with our new currency variable. Now I have a string with two variables inside of it. Let's see what happens when I run this script. You'll notice that the variable name is printed out, not the value that we put in. That is a big difference between single and double quotes. Now there are a few other things that we need to cover using single quotes. Since we're using the single quote to encase our entire string, what happens when we need to use that single quote inside of our string? For an example, I have a string value of St. Patrick's Day. Now if I try to print this out, it's going to throw an error. I'm going to run this script, Shift+F6, and you'll see that we have a parse error. That single quote in St. Patrick's Day is basically terminating the string after St. Patrick leaving the s Day just to hang out there. So how do we fix this situation? We use the backslash. If we put a backslash in front of the single quote, we'll be able to display the entire string value correctly. Let's go ahead and put in that backslash, and let's run it again. You'll notice our variable prints out correctly with no errors. Single quotes will also print out the literal escape sequences instead of evaluating them. In previous modules, we've used the \n to print a new line to make our output a little bit more readable. If we were to use the \n inside of a single quote, it would actually print out \n. It would not give us a new line. Let's go ahead and see this in action. I'm going to add a \n to the end of our St. Patrick\'s Day string. Let's go ahead and print this out, and you'll notice in the output window, here's our \n. The main thing to remember when using single quotes for string values is that it will print everything out as is. None of the text inside will be evaluated, including the variables and including any type of escape sequence. Let's move on to double quote strings, and we'll expound on the knowledge we already know and have learned from the previous modules.

  30. Double Quoted Strings (Demo) Since we already know that strings can be printed out with double quotes, we're going to jump right in into putting a variable inside of a string. Here I have the same string from the single quote example. I replaced the single quotes with double quotes. Let's go ahead and run this script. Now you'll notice that instead of actually printing the variable name, it prints the contents of the variable. So the value has been printed out in our string, and now our string makes sense. When you use double quotes, the string is evaluated. That means that anything within your string will be evaluated for any value that it has. In this case, our currency variable was evaluated with the value of penny. So the issue with this is what happens when we need to add to something onto the value inside of our string? For example, I want to create a string that says 2nd place. I want the variable to be an integer, but I need to add on the ending nd for 2nd. To demonstrate the problem, I'm going to create a variable, and I'm going to give it an integer value of 2. Now I'm going to create a string, and I'm just going to print this string out, and I'm going to put in my variable name. Immediately following it, I'm going to put nd for 2nd, and then I'm just going to type a space and then place. Let's go ahead and run this. You'll notice the only thing that's printed out is place because the PHP interpreter thinks that it is looking for a variable varnd. There's no variable varnd declared, so it just prints out nothing for that variable, and then finishes off printing out the rest of the string. So what we need to do is tell the PHP interpreter that we have a variable here. In order to do this, we're going to add curly brackets around the variable, so I'm going to go ahead and put in these curly brackets. And now when we run this, we're going to see that it actually says 2nd place, and we can see in the output window it does say 2nd place. There's a second way that we can also fix this situation where we have a variable followed immediately by characters, and that's concatenation, or concat for short. Now most languages use a plus sign for concatenation. In PHP, we use the period. I'm going to alter this string. I'm going to take out the variable, and I'm going to take out the squiggly brackets so my string is just left with nd place. Now in front I'm going to add my variable, and in between my variable and my string I'm just going to put a period, and that means I'm going to concat the string to my variable. And when I run this, I'll get the same results as my previous example. Not bad. Now this concatenation will also work with single quoted strings. Now the squiggly brackets inside of our previous example will not work with single quoted strings. Now you might be wondering about the single quote inside of a double quote. Well in this case there's no issue. We can put all of the single quotes that we want, and they'll still print out. I'm going to use the same St. Patrick's Day string that I used in the single quote demo, and in this case I'm going to print it out exactly as is with the single quote inside. Notice the output. It didn't throw an error because any single quote inside of a double quote string will print out just fine. Even though the single quotes are not an issue with a double quote string, the double quote is an issue. If you have a double quote, we do the exact same thing that we did with the single quotes. We put in a backslash right before the double quote. I'm going to use the St. Patrick's Day string and just alter the single quote right before the S and replace it with a double quote. You'll notice right away that the editor is already throwing a warning saying that there's something wrong with this string. And if we actually were to run it, it would throw an error, but instead we're going to fix this by putting a backlash right before that double quote. Now we're going to go ahead and run it. You'll see that it says St. Patrick"s Day, but instead of that single quote, it has the double quote. Now what about our escape characters, such as the \n? Well when you put them in double quotes, they're evaluated, so in this case we would get a new line printed. Even though we've seen this in the other modules, we're going to go ahead and print out a new line here. I'm going to set my miscellaneous variable to be equal to a new line. Again, to create a new line it's \n. And I'm just going to run this script, and here in the output window you'll see our extra line was printed. The main thing to remember about single quote strings and double quote strings is that double quote strings are evaluated, whereas single quote strings are not. In the next clip, we're going to discuss heredoc. This is another way to have strings inside of PHP.

  31. Here Document (Demo) Another way to use strings inside of PHP is the heredoc. The most important thing to remember about the heredoc text and setting up a heredoc is the syntax. First we need three less-than signs followed by an identifier. I'll show you what I mean. So here's my three less-than signs, and my identifier can be anything that I want. Typical identifiers are all uppercase. In this case, I'm going to use EOT, End Of Text. So my identifier is going to start out with an EOT. Immediately after my identifier I'm going to put in the text that I want, and this can be anything formatted any way. The thing to remember about the heredoc text is that it acts just like a double quoted string. Now I have a block of text ready to go, so I'm just going to go ahead and paste this in. So here's my quote. I'm going to enter a new line. Now on this new line I will put the same identifier that I started out the heredoc with. Now here's the catch. The identifier has to be the only thing on the entire line, including extra spaces, so I type in the identifier, plus the semicolon, and nothing else. There can be no space before the identifier or after the identifier. I'll show you what I mean. So here's the identifier working correctly, so I have my beginning identifier, my closing identifier, I have my text. I'm going to go ahead and run this. Here's the output. Notice that the quote is printed up exactly how it is formatted inside of the heredoc. That's another bonus of using the heredoc if you have a lot of text that needs to be formatted in a specific way. Now I want to show you the error that gets thrown when you have a space or any extra characters on that ending identifier in the heredoc. So I'm just going to put a space right after the semicolon, something that you wouldn't normally do, but it's not easily detectable. Now when I run this, you'll notice that the parse error says unexpected end of file, so the error that is given, it doesn't even give the correct line number where the error occurs. This is just one thing to keep in mind when you're using the heredoc. Always double-check the syntax. In our next clip, we're going to cover the print and echo keywords and the differences between the two.

  32. print() (Demo) Print and echo are not actually functions. They are language constructs, so we don't have to use parentheses. And this entire time up until now we have not used parentheses, but I want to show you that you can use parentheses. So here I have my standard print statement, and you'll notice I'm using the print keyword this time. I can use it as is. Let's go ahead and run this script, and it comes out as we expected. Let's go ahead and put parentheses around this string, and we're going to go ahead and run it. You'll notice it printed out the exact same. For the most part, print and echo can be interchanged. There has been some discussion as to which is faster. I believe that echo is ever so slightly faster than print, but that the results are basically negligible. There's one thing that echo can do that print can't do, and that is to print up more than one parameter. Now I already have a string that's broken up into different parameters. I'm going to go ahead and paste this right after my echo keyword. Notice that I separate everything with a comma. So you can have as many parameters passed into echo as you wish; just separate everything out with a comma. I'm going to go ahead and run this, and you'll notice it prints out everything, but all pushed together. Now let's go ahead and put the proper spaces in so that we can actually have a readable sentence. Let's go ahead and run this script. Now our sentence looks appropriate. Now you're probably asking what do I use? Do I use print? Do I use echo? And the answer is it doesn't matter as long as you're consistent in your code. In our next clip, we're going to learn how to change our string case to be either all uppercase or lowercase.

  33. Changing Case (Demo) PHP has a bunch of built-in functions for string manipulation. The first one we'll cover in this clip is strtoupper. Strtoupper takes one required parameter of string type, and it returns a string value. Here I already have my variable with a string value. I'm also printing it up immediately. So now I want to change the case to be all uppercase. Now I'm going to add one line of code in between my variable and printing of my variable. I'm going to use this same variable to store my value that has been altered with the strtoupper function. Let me go ahead and type my variable, and then I set it equal to. And now this is where I'm going to put in the function call, strtoupper, all together, all lowercase. That's the function call. And then I'm going to pass in a parameter. That parameter is my variable, which is of type string. So now when I print this, the entire value of my variable will be all uppercase. Now remember, it's all alphabetic characters that will be uppercase. So let's go ahead and run this script, and notice in our output window the entire string is uppercase. Now the next function I want to cover is strtolower. The strtolower works in the exact same way, except for it lowercases everything. The function call is strtolower, all lowercase, and all together. I can easily modify my strtoupper function call by just changing out upper to lower. Now if I run this again, you'll see in my output window everything in the string is now lowercase. That's it, two simple functions that are built into PHP. In the next clip, we're going to learn how to find the length of a string.

  34. strlen() (Demo) Sometimes in a script you need to know the length of the string that you're dealing with. PHP has a built-in function called strlen. Strlen takes one parameter, which is of type string, and it returns an integer of the length of that string. So I already have a variable here with a string value, and now I'm going to make a new variable, and I'm going to call it length. And I'm going to set it equal to, and then I'm going to type in the new PHP function that we're learning, which is strlen. Now the function is abbreviated, so we're going to use strlen, which is short for string length. Then we're going to pass in a parameter, and that's going to be our variable whose value is a string value. Now we're going to go ahead and print out our variable length. So if we run this script, you'll see that we have a value here indicating the length of the string, so it's counting how many characters and spaces are within that string. That's it for string length. In our next clip, we're going to cover string position.

  35. strpos() (Demo) This next function, strpos, will find a particular character or set of characters inside of a string. So I already have a variable here holding my string value. Now if I wanted to find a specific position of a character, I would use the strpos function from PHP. The string position function in PHP is strpos. Now for this example I'm just going to print out the results of the function, so I'm going to type in echo strpos. Now this function takes two required parameters and one optional parameter. Let's go over the required parameters first. The first parameter is the string that you want to search in, also known as the haystack. Let's go ahead and put in our variable that we've already set with a string. The second required parameter is the character or characters that we're looking for in our string. So for our second parameter, we're going to search for the word fear. Now we just need to close out our function, add the semicolon, and let's go ahead and run this. Now the result is the position of where this word appears in our string. So in this case, it's saying at the 25th position the word fear appears. Now the string position starts out at 0. So if we're looking at our string, the position of the very first letter C is 0, so for our word fear, the position 25 is indicated where the F starts in our word fear. So what happens when we need to find the second appearance of a character or of a word inside of our string? That's where the optional third parameter comes into play. Right after the needle parameter, we will put in an offset parameter. This offset is basically the offset position of where you want to start looking from. So we know that our word fear starts at the position of 25, but we want to try and find the second word fear. So if I go ahead and put an offset of 26, it will then look for the next occurrence of fear inside of our string starting at the position 26. Now if I run this, the result of the second position of the word fear is 42, which is the position of the second time that fear appears within our string. Now let's discuss finding single characters inside of a string using string position. Let's go ahead and type out a new print statement, so we're just going to type echo, and then strpos, and we'll use our variable quote. Now we're going to go ahead and search for the letter C. Now when we run this, you'll notice the first instance of our C is at 19. This is because strpos is case sensitive. To demonstrate this, let's go ahead and search for our capital C, which happens to be the very first letter in our string. Let's go ahead and run this, and in the output window you'll notice that the capital C is in position 0. Now what happens if we search for a letter that is not inside of our string? After a quick glance at our string, I can see that it does not contain the letter Z, so let's go ahead and search for that letter. Now we'll run it. The return result for a character that is not found inside of the string is an empty string, and you can see that here in our output window. It is important to remember what is returned when the character is not found and when the character is in position 0. That's it for string position. In our next clip, we're going to cover string replace.

  36. str_replace() (Demo) Now we've moved on to string replace. String replace will replace one value with another value inside of a string. This function requires three parameters. The first is the value that you are looking for in the string to replace. The second parameter is the replacement value. This is the value that you're going to replace with the value you looked for inside of the string. The third parameter is the string itself. Let's go ahead and use this function. I already have my variable with my string value. I'm going to create a new variable right below it, and now I'm going to set it to str_replace. The string replace function is str_replace. Now you might notice that there's an underscore in this PHP function. This is true for a handful of the functions in PHP. As you get to know these functions, you'll start remembering which ones have underscores and which ones don't. Now after we type the function name, our first required parameter will be the value that we are looking for in our string to replace. In this instance, we're going to replace the word be. Now our second parameter is going to be the value we want to replace be with. So to make this statement somewhat readable, we're going to replace it with know. Our third required parameter is the string that we're going to be searching, so I'm just going to type in the variable of our string. Now we just need to print out our variable, and then we're going to go ahead and run it. So now we have our string being printed out with the replaced value, so instead of the word be, we now have the word know. Now the str_replace can be used with more complex types such as arrays. We're not going to cover that in this clip or this module, but there is one extra thing that I would like to cover with str_replace, that is the fourth parameter. The fourth parameter is optional, and it's technically not a parameter that we're passing in. It's a parameter we're getting back from the PHP function itself. In order to use the fourth parameter, we give it a variable name. So this variable name could be anything, but we also want the variable name to reflect what it is being used for. In this instance, the variable that we are going to provide is the count. This is the count of how many times in our example the word be is replaced. So I'm just going to put the variable name down as count. Now you'll notice I haven't declared it anywhere. This is a variable that's being declared in the PHP function and then passed back to us. The typical term that is used is called passed by reference. Once we run this script, we can now print out the variable that we're using as a passed by reference. So the function itself is returning a value, and now we have a variable that is being returned to us with the value of how many times it replaced the word be. So let's go ahead and print out the variable count, and we're going to run this script, and you'll see that it's coming back with the value of 2. Two times was the word be replaced inside of our string with the word know. That fourth parameter is a little complex to understand, but just remember the function is returning another value back to us, and we need to store it in a variable. Now that we're done with str_replace, we're going to move on to substrings.

  37. substr() (Demo) The next function I'd like to cover is substr. This function will take a string and create a substring from the specific location that you provide. So I already have my variable here and a string value, and I'm just going to go ahead and print out the substr function. The substr function returns a string value. So I'm just going to type in echo, and then the function name is substr. Now this substr function takes two required parameters and has an optional third. We're going to focus on the first two required parameters. The first parameter is the string value that you're going to create a substring from, so in this case I'll just enter in my variable. The next parameter is the start location of where I want my substring to start. Now just like with the strpos function, the very first start position is 0. So if I wanted to take the entire string, I would put in 0, which would make this function not needed. So let's go ahead and put in a different value. We're going to put in 4. So at the fourth position is where our substring will start. Let's go ahead and run this. You'll notice in our output window that our substring starts four characters over. In this case, starting four characters over eliminates the entire first word of our string. Now what happens if we put in a negative number into the substring? If we use a negative number as our start character, what happens is we start four characters in from the end of the string. So if we run this, we get the space, go, and the period. Those are our four characters from the end. Now let's talk about the third optional parameter. The third optional parameter declares how many characters that we actually want to take. So if we start at the third position and take 5 characters, we're going to end up with the Y, the space, the TH, and the O. Let's go ahead and run this, and you can see we were correct. Now I bet you're wondering what happens if we put a negative number on that third parameter. The start position can be anything you want, so we'll keep our 3, and now we'll just take our 5 character and make it a -5 character. Now if we run this, our substring in the output window is starting at position 3, and it ends 5 characters before the end of the string. That's it for substrings. In our next clip, we're going to go over our final function for this module, which is string split.

  38. str_split() (Demo) Well, we are at our last string function that we will learn for this module. This string function is str_split. This takes a string and converts it to an array. I already have my variable with my string value. Now I'm just going to create a new variable, and I'm going to set it equal to my str_split function. The string split function is str_split. This function takes one required parameter and a second optional parameter. The first and only parameter that is required is the actual string that you want to convert into an array. Let's go ahead and put in our variable of our string. Now our new variable is holding an array. In order to print out an array in PHP, and to see the contents of the array, we need to use a new print function. This print function is called print_r. This function, print_r, makes the variable print out in human, readable form. For us, we only need to pass it our array variable for it to print out. So go ahead and let's type in our array variable, and let's go ahead and run this. You'll notice that using the str_split takes our string and gives each individual character its own value in the array. Now we'll be covering arrays in the next module, but here is your first look at what an array looks like. Sometimes we do not want to split up the string by its individual character. We want to split it up by chunks of strings. That's where the second parameter comes into play. Any integer value that we provide will split our string up by that string size. I'm going to go ahead and put 8. The str_split will split up my string value into an array where each value is 8 characters long. Let's go ahead and run this. Using our print_r, we can see the readable value of our array. If you look at each of the values in the array, they're all 8 characters in length. That's it for str_split and the end of our demos for this particular module.

  39. Summary You made it. We finished the module. We learned about basic string creation. This included single quote strings, double quote strings, and the heardoc. We also covered the print function. We covered a few built-in PHP string functions. Those included strtolower, strtoupper, strlen, strpos, str_replace, substr, and str_split. Now we're on to the last general type of PHP, arrays.

  40. Arrays Overview Arrays are an invaluable type in the PHP programming language. They become very useful when working with database records, which will covered in a later module. In this module we will cover a lot of the basics of the array type, including what is an array and the creation of an array. We will learn how to access the values inside of an array. And just like with the string type, the array type has a bunch of built-in functions. A handful of these will be covered throughout the module. There aren't quite as many built-in functions as there were with the string type, but there is enough to have another scrolling view of all of the array functions PHP has to offer. Again, the highlighted function calls will be covered in this module. And for those who like facts, that is a total of 79 functions that deal solely with the array type.

  41. About Arrays So what is an array? Think of an array as a collection of types. The array can hold any type, which means it can contain strings, integers, floating points, and even other arrays. Each of these values inside of an array can be accessed via a related key. Common terminology associated with arrays is a key value pair. There are two ways you can create an array. One is by using the array language construct, which is array followed by parentheses, and the other way it to use the square bracket syntax. In our next clip, we will create arrays using these two methods and cover the basics of an indexed array.

  42. Indexed Arrays (Demo) Let's jump right in and create some arrays. I'm going to set up a variable here, and I'm going to have it equal to. Then I'm going to type the name array. Following the keyword array, I'm going to use an open and close parenthesis followed by my semicolon. Now if I were to leave this as is, this would be creating an empty array. Now we're not going to leave this empty. I have some content that I'm going to paste in here. So here's my content, and you'll notice each of my string values is separated by a comma. Any time you're using an array, everything needs to be separated by commas. And it doesn't matter what type you're using. It could be integer, floating points, strings. Everything needs to be separated by a comma. Let's go ahead and print this array. Remember our print_r function from the last module? We're going to use that again. So I'm just going to type print_r, and then I'm going to pass in our array to be printed. Let's go ahead and run this. So here we have an indexed array. These are the keys, and here are our values. We did not assign any of the keys. The keys were assigned by PHP. Now we created an array using the array keyword. Let's go ahead and create another array using different syntax. I'm going to create another variable, and I'm going to set it equal to. And instead of using the keyword array, I'm going to use an open and close square bracket. Now I have some content. It's strings again, and I'm just going to paste it in here. Let's go ahead and print out this array. I'm going to use the print_r function. I'm just going to place it right before our current print_r and pass in our new array variable. Let's go ahead and run this. And again, we see all of the values, and here are the keys. We did not assign any of the keys. PHP assigned these keys, thus making this an indexed array. Now just to demonstrate that arrays can hold different types, let's create a third array. So I'm just going to set my variable, and I'm going to use the square bracket syntax. Let's go ahead and add our first value. I'm going to choose an integer, insert my comma, and I'm going to follow that by a floating point. Don't forget the comma. Now we've already seen strings, but I'm going to add another string in here followed by a comma. And now I'm going to put a Boolean value. And the last element does not need a comma, so now we can go ahead and print out this array. Let's go ahead and run this, and you'll see all of our values, and you'll see all of the keys. That's it for index array and array creation. Let's go ahead and move on to associative arrays.

  43. Associative Arrays (Demo) Anytime you alter the key in an array, you have turned the indexed array into an associative array. Here I have an array that is an associative array. You'll notice each of my values is proceeded by a string that acts as my key value. Now in order to use the key with the value, we separate them by the equal sign and a greater-than sign. So this is basically saying this key refers to this value. Now I have three key value pairs here. Let's go ahead and print out our array. I'm just going to type the print_r function, pass in our array variable, and now our printout is a little bit different than the indexed arrays. You'll notice the values on the right-hand side, but if you look to the left-hand side, you'll see that all of our keys, which used to be integers, are actually string values now. Each key is referring to a specific value. Now there's a lot to be done with keys. Let's say I wanted to change out one of these keys and put in an integer. Even though I'm using an integer, it does not make this an indexed array. Now when I run this, you'll see the keys, and you'll see our values, but notice the one key now instead of a string variable is an integer. I'm going to show you one more thing with associative arrays. Let's add another value to our array. So at the very end here I'm going to add a comma, and now I'm going to set a value. I'm not going to give it any key. Now typically we would say any value that is not assigned a key would be assigned the very first key value just like in an indexed array, which would be 0. Let's go ahead and run this and see what actually happens. Notice our last value has an integer for a key, but that the key value is 11. So we can take any integer, insert it in one location, and anything that has no key assigned to it will automatically be increased for the next key. This is just something to keep in mind when you're creating associative arrays, especially when you're reassigning keys with integer values. In the next clip, we're going to talk about how we can access each of these values by the key that is assigned to it.

  44. array_key_exists() (Demo) Accessing the values inside of an array is a lot easier than you might think. Here I have two different arrays. One is an indexed array, and the other is an associative array. Let's first talk about the indexed array. Each of these values has a key assigned to it. We know that each of the keys is 0, 1, 2 because it's an indexed array. The keys are assigned by PHP. They start out with 0 for the first value. If we wanted to access the second value inside of our indexed array, we just need to type out the variable. We're going to print this out, so we can either use the echo or print keyword. I'm just going to use echo. Then I type the array variable name. And then to access any of the values, we use square brackets right after the variable name. Now inside of the square bracket for indexed arrays, we put in the integer number that we want to access. If we want to get the second value inside of our array, we need to put in the integer 1. Remember indexed arrays start with a 0, so our second value would be 1. So here we have our print statement. Let's go ahead and run it. Notice the output? This is the exact value of the second value in our indexed array. That's it, super easy. Now let's look at our associative array. Now we do the exact same thing. We want to type out our array variable, so I'm just going to echo the array variable, and I'm going to use the square brackets again. Now since our associative array doesn't have integers to access the values, we need to type in the exact key that we want to access, so let's go ahead and type in one of the keys of the values inside of our array. Now if we go ahead and print this, in our output window you now see the value of that particular key inside of our array. Accessing key values is very simple. The problem that we run into is does that particular key exist? That's where the function call array_key_exists comes into play. So we're just going to print the contents of this function immediately, so go ahead and we're going to type in echo, and then the function call is array_key_exists with our parentheses. Now this takes two required parameters. The first required parameter is the key that you're trying to access. So if we were trying to access a key in our index array, we could put something like 5. We definitely know that there's no key 5. Then we follow that required parameter with our second required parameter, which is the array variable. Now let's go ahead and print this out. Now you'll notice nothing was printed. Remember in PHP when nothing is printed from a function call, that indicates that the function call returns false. Now if we were to look for a specific key that was in our array, we would get the result of 1. So let's go ahead and do that. We know that there's a key 2 inside of our indexed array. So we just need to go ahead and run this, and sure enough in our output window there's a 1. Now the same thing can work for associative arrays. Instead of the integer, we just put in the actual string value of that key. Here's our string value of our key. Here's our array variable. Let's go ahead and print this, and you'll see in the output window we're getting a 1 indicating that key exists inside of our array. In the next clip, we're going to talk about how to find if a value is inside of an array.

  45. in_array() (Demo) We've learned how to find if a key exists inside of an array. Now let's look to see if a value exists inside of an array. I have an indexed array here. Now the following doesn't matter whether the array is indexed or associative. I chose index because it's a little bit more readable for this example. In order to find if a value is inside of an array, we use the built-in function in_array. Now we can print out the contents immediately from the function call. So you can use either print or echo. I'm going to use echo. Now the function is in_array, and then we have our parentheses followed by our semicolon. Now the in_array function takes two required parameters and an optional third. The first required parameter is the value that you're looking for. So in our case this is an array of authors. I'm going to put in an author that's in our list. Now the second required parameter is the array variable, so I'm just going to type out our array variable, and now we can run it to see if our value is inside of our array. Now in the output window you'll see a 1. Remember if it returns 1 it means it's true indicating that our author is inside of the array. Now let's go ahead and put in a different author that is not inside of our array. Now when we run this, you'll notice that nothing is printed out. Remember when nothing is printed out, that means the function has evaluated as false. Now let's go over that third parameter. The third parameter also checks if the type is the same. I'm going to demonstrate this with an integer, so let's go ahead and add an integer value inside of our authors array. So let's go ahead and switch our value that we're looking for in our array to be this number. Now in order to use the third parameter, we just add in a Boolean value. So it defaults to false, so we need to add in true saying that we want to check not only the value, but that the type is the same. Now we have an integer inside of our authors array, and we're looking for an integer. This should return 1. Sure enough in our output window you'll see a 1 indicating that it found not only the value to be inside of the array, but that the type was the same. Let's go ahead and change the value that we're looking for. Instead of being 13, let's change it to a string 13. Let's go ahead and run this. You'll notice the output is false indicating that it did not find the value 13 of type string inside of our array. That's it for in_array. In the next clip, we're going to learn how to add values to our array.

  46. array_push() (Demo) There are two ways that you can add new items to an array. I already have an array here that we're going to work with. The first method is the array_push function. The array_push returns an integer with the count of how many items are now in the array. Since we aren't worried with how many items are in the array, we are not going to save the data to a variable. We also don't have to worry about updating the array variable itself. The reason for this is because the variable that you pass into array_push is being passed by reference. When it's altered, it alters the variable here locally instead of inside the function. You just have to type the actual function name. In this case, the function name is array_push. Now this takes two required parameters. The first parameter is the array variable, so let's go ahead and type in our array variable. The second parameter is the new value you want to add to the array. In our case, we're just going to add another author. Now we just need to print out our array, so we have print_r and then our array variable. Now when we run this, you'll notice in the output window here is our new value that we added to our array. Now the second method to add values to an array uses the square brackets, so let's go ahead and use this in between our print statement and our array_push function. So in order to use the square brackets, I just use our array variable name. Immediately following the variable name, I use the open and closed square brackets, and then I set it equal to the value that I want to add to the array. In this case, we're going to add another author's name. Now when I run this, you'll notice in the output window here is our array and all of the contents. We have two new items added to our original array, one using the array_push function and the other using the square bracket syntax. Now the preferred method of adding elements to an array is the square brackets. The reason is if the array has not been declared, if you use array_push, an error will be thrown. When the square brackets are used with an array that has not been declared, the array is created, and then the element is added on to the array. As you start adding more elements to an array, you need to keep in mind that the array_push will only add indexed values. That means if you have an associative array and do an array push on that associative array, the key will not be a string value. It will be the next available integer for the key, which in most cases would be 0. If you want to add a key value pair to an associative array, you just need to alter the square bracket syntax that we demonstrated earlier. So instead of the empty square brackets, we would actually put the key that we want to be associated with the value. For example, I can take this authors with the empty square brackets and alter it to be an associative key value pair. Inside of the empty brackets I now just type the string that I want to use as my key value. These are just a few things to keep in mind when you're working with adding elements to an array. That's it for adding new elements to an array. Now we're going to move on and learn how to remove those elements from an array.

  47. array_pop() (Demo) Now that we know how to add items to an array, we need to know how to remove those items from an array. In this module, we're going to cover two ways to remove an item from an array. The first method is using the built-in array_pop function. Now the array_pop function takes one required parameter. That required parameter is the array itself. The idea behind the array_pop function is that it removes the very last element in the array. Now when it removes the item from the array, you can save it into a variable, so let's go ahead and set this up so we're storing the element that's removed into a variable. I'm just going to create a variable here, and I'm going to set it equal to, and the array_pop function is array_pop. Now we just need to pass in our array variable. And that's it. Now we can print out the last item that was removed from the array. We just need to type echo and then our variable name. Now let's go ahead and run this. Now you'll see in our output window there's the last item in our author array. Now if we go ahead and print our array, so I'm just going to type our print_r function, pass in our variable, let's go ahead and run this, now in the output window we see our value that was removed, and now we see the array with one less item in it. Array_pop is great for removing the last item in the array, but sometimes we want to remove a specific item in our array. In that case, we want to use a function called unset. We're going to learn about it in the next clip.

  48. unset() (Demo) The unset function is not specific just for arrays. It can be used on any variable type. So here I have my indexed array. Now I want to be able to use the unset function on a specific item within this array. In order to do that, I just need to type the function's name, which is unset, and then I just need to pass in the one required parameter, which is the variable that I want to remove. In this case, I want to remove a specific item from my indexed array. We already know how to access specific items within an array, so I just need to type in my array variable and then the key of the item that I wish to remove. So let's go ahead and remove the second item inside of our array. And remember, the second item is 1. In order to see that the array item has been removed, we need to print the array, so let's go ahead and put our print_r function and pass in our array variable. Now if I go ahead and run this, you'll see that our array is minus 1 item, and you'll notice the keys are 0 and 2, so our unset can be targeted to specific items within our array. Now unset has the ability to chain variables together with a comma, so I can actually remove two, three, four variables at a time, and I just need to separate everything by a comma. Let's go ahead and remove another item from our indexed array. Let's remove the very first item. So we just type in our array name, and then our square brackets, and we're removing the first element, which is key 0. And now if we run this, our array only has one item in it now. This will work the exact same way if we had an associative array. So I'm just going to paste in my associative array, and now I want to be able to unset one of these items in the array. Now instead of passing in the key, which is an integer, we just need to use our key, which is a string value. So I just need to type in unset, and then my variable name, and in the square brackets I just need to type in the key that I wish to remove. And in this case, our key is a string. And now I need to print out my array so we can see that we've removed that item from it, so I'm going to type print_r and then my variable name. And now that's it. So let's go ahead and run this, and now you'll notice here is our associative array minus the one item that we've removed. Earlier I stated that this could be used for any variable type, including an entire array, so let's go ahead and unset our indexed array. And since we have both of these printing out at the bottom, you'll notice that now, once we've unset it, the only thing that's going to print out is our associative array. So let's go ahead and run this, and sure enough here in our output window there's only our associative array being printed. That's because we've unset our indexed array. You have to think of unset as in removing or deleting or as if the variable had never been created. In our next clip, we're going to learn how to sort our arrays.

  49. Sorting Arrays (Demo) At some point, you might want to sort an array. Now there are many ways to sort an array. We're going to cover three different ways that you can sort a specific array. Those built-in functions that we'll cover are sort, ksort, and asort. So here I have two different arrays. One is an indexed array, and the other is an associative array. We're going to focus on the indexed array first. In order to sort an array, you just need to call the sort function. You don't need to save it to any variable, and it can be printed up right afterwards. In order to call the sort function, I just type in the word sort. And it takes one required parameter, and that's the variable of the array that you wish to sort. So in this case, we're going to sort our indexed array, so I'm just going to type in the variable name. And that's it. But now we need to be able to see our array sorted, so let's go ahead and print that out. Now we get to run it. If we look in the output window, you'll notice that our array is now sorted alphabetically. Let's look at the original array. You'll notice that nothing is in alphabetical order, but now in our printout, because we've sorted this array, it sorts all of the values in alphabetical order. Easy enough. Now the sort does take one optional parameter. This parameter is called sort_flags, and it can be used to modify the sorting behavior of the sort function. We're not going to cover those flags in this course, but know that there are different ways that you can sort inside of the sort function. Now if you use a regular sort function on an associative array, all of the key values that you have will be replaced with indexed values. So it will sort the associative array, but then you end up with an indexed array. The next type of function that we have to sort arrays is the asort. Now this takes two parameters, the first being a required parameter, which is the array you wish to sort, and the second parameter, which is optional is the sort_flags. Again, we will not be covering that in this course. So the asort performs a little bit of a different type of a sort in that it preserves the keys of the values of the array. So when we did a regular sort on our indexed arrays, you'll notice that the array values were sorted, and the indexed values were reassigned. Well when you have the asort, it preserves all of the key values. This is perfect for when dealing with associative arrays. That way the key values aren't erased and replaced with integers. Before we run this on our associative array, let's go ahead and run this on our index array. So the asort function is just asort, so we can take our sort function here and just put an A in front of it, and we're ready to go. We already have our print statement, so let's go ahead and run this. Now let's look at the keys in the output window. Notice that they're not incremental. They jump around. This is because the keys are preserved. Now if we look at the original, we know the keys of our indexed array, and if we look at the very last item in our array, we know that key is 4 because it's the fifth item in our array. And if we look at the output, right next to Louisa May Alcott, you'll see that the key is 4. The keys are preserved when using the asort. This makes it ideal for associative arrays, but not the most practical for indexed. Let's go ahead and pass in our associative array variable and see what happens. Let's go ahead and run this. And if we look in the output, you'll see that all of the keys are intact, and they're corresponding to the correct value. When you need to sort an associative array, using the asort is your best bet. The last function that we're going to cover about sorting is the ksort. The ksort will sort the array by its key value and will maintain that key to data correlation. Since an indexed array is already sorted by its key, there's rarely a need to use the ksort with the indexed array, so we're just going to focus using the ksort with our associative array. The ksort, like the regular sort and the asort, takes two parameters, the first being the required array that you would like to sort, and the second is the sort_flags, which we won't be covering in this course. All we need to do is change our asort to be a ksort. So now we already have our associative array as the parameter being passed in. We just need to run this. If we look down in the output window, you'll see that our array is printing up, but now it's sorted by its key value. That's it for the ksort. In our next clip, we're going to learn how to count the number of items inside of our array.

  50. count() (Demo) This is the last built-in array function that we'll be covering in this module, and that is count. The count function takes two parameters. The first is the required parameter, which is the array that you want to count the number of items that are in it. The second parameter is optional and deals with multi-dimensional arrays. We're not going to cover multi-dimensional arrays in this clip, but we will demonstrate how it counts those items inside of a multi-dimensional array. I already have an array here, and we're going to use count on this particular array. Count returns an integer value. We're going to print this function out; we're not going to save it to a variable. So I'm just going to type in echo, and then the count function is just the word count, and then we just need to pass in the required parameter, which is our array variable. Let's go ahead and run this. And if we look in the output window, you'll see that our result is 5. There are 5 elements in our array. And if we look at the original array, we can count those ourselves. Now if we have a really long array, this count function becomes extremely useful. I'm going to paste in my multi-dimensional array. We're going to cover this a little bit more in detail later in this module, but just so you know, this is basically an array of arrays. Let's go ahead and run the count on this particular array and see what happens. Now you'll notice the output says 2. It's telling me that there are 2 items in this array. Now we can clearly see that there are more elements in this array than just two. It's counting the first two values in the array, but we want it to count all of the elements in all of the arrays located inside of our main array. Now the second parameter, which is optional, will help us to count every single element in this array, so we can either set it to 1 saying to yes count all of these elements recursively, or we can actually pass in the constant that is set up by PHP, and that constant is called COUNT_RECURSIVE. Let's go ahead and run it with the optional 1, and let's look at the output. Now the count is saying 16. That is a big difference over the 2 that we just recorded. Now if you don't want to put in a 1 as the optional parameter, we can always use that constant, COUNT_RECURSIVE. Remember, when using the constants in PHP, they're all uppercase. Now this is one that is set by PHP, so we don't have to declare it anywhere. We just have the opportunity to use it. We're just going to type COUNT_RECURSIVE. Make sure it's all uppercase. And now we're going to go ahead and run it, and you'll see the results are the exact same as when we put a 1 as that optional parameter. It doesn't matter which way you use this optional parameter, whether you use the constant or whether you use the 1. As long as you're consistent with your code, that's what matters. In our next clip, we're going to cover the foreach loop, which is specifically designed to deal with arrays.

  51. Foreach Loop (Demo) The foreach loop is designed specifically for arrays. The idea is that we want to loop through each individual item in the array and store that item to a temporary variable where we can do something with that temporary variable. So let's go ahead and jump right in and create our foreach loop. All foreach loops start out with the word foreach and then an open parenthesis. The very first item in this parenthesis is the array variable, so let's go ahead and put that in there. Now each of the elements in the array needs to be assigned a temporary variable, so we're literally going to write as and then our temporary variable name. Now this variable name can be anything that you want. I'm just going to put val for short. This is going to be the value of each of my array elements. Then we put a closing parenthesis. Immediately following the closed parenthesis, we have the opening and closing curly brackets. This is kind of reminiscent of our function calls. Now inside of our curly brackets, we can do anything that we want with our temp variable. In our case, we're just going to go ahead and print it out, so I'm just going to type echo, and then type out our temp variable, which is val. Now since it's going to print out the value of each of our array elements, I'm going to concat a \n onto it so they'll each print out on their own line. That's it for the foreach loop. Let's go ahead and run this. If you look in the output window, each of the values in our array have been printed out on their own line. Now I bet you're wondering what happens when I'm using an associative array such as we have here. I want to be able to do something with the keys inside of my array. With a few modifications to our foreach loop, this is possible to pull out the keys of each of the elements inside of our array. So after the word as in our foreach loop, we will write a new variable, which is another temp variable that will hold the key value, so my temp variable is going to be called key. And then we're going to use the same syntax that is used in our associate arrays, the equal sign, and then the greater-than sign. So now we have two temp variables that match each of the associative array elements. We have a key, and we have a value. So now in order to print out that key, I'm just going to alter my print statement and concat my key onto it, and now I'm going to go ahead and run it. If you look in the output window, you'll not only see the value that we have in our array, but now you'll see the key. That's it for the foreach loop. In the next clip, we're going to talk about multi-dimensional arrays.

  52. Multi-dimensional Array (Demo) In my opinion, one of PHP's best features is the array and the ability to hold an array of arrays. This is also known as a multi-dimensional array. Here I have an example of a multi-dimensional array. You'll notice there are three levels of arrays. Let's view this in a little bit more of a readable format. I'm going to go ahead and print out this multi-dimensional array. It's printed out in the exact same way as all of the other arrays are printed out, using the print_r function. In the output window, our array is now displayed in a much more readable format. So you have the initial array; you have the next associative array elements. This is an associative array, so we have our key elements defined, and their value is an array, and that has an associative array key, which is also holding an array. So we have these nested arrays inside of our main authors array. Multi-dimensional arrays just take practice, and the more you use them, the more you'll be comfortable with them. I'm going to show you how to access some of the values inside of a multi-dimensional array. So we've just printed out this array. Now let's go ahead and access the very first value. To access any first value of a multi-dimensional array, we type in the square brackets and then the key name. So in this case, we're going to type in male. Now let's go ahead and print this out. In the output window, we see everything that is stored in the value of the key Male. Now we can take it one step further and access one of the male's key values. In order to do that, we just add another square bracket next to the square bracket that we've already declared. So in this case, we're going to look inside Mark Twain. Now let's go ahead and run this. This prints out the value of Mark Twain, which is an array. Now we can actually grab one of those array values. We add another square bracket next to Mark Twain, and since this is an index array, we need to use a key of either 0 or 1. Let's go ahead and use 1. Let's go ahead and run this. Now in our output window we have a single value, which is nested deep inside of our multi-dimensional array. This is how you access the different levels inside of a multi-dimensional array. So that's basically multi-dimensional arrays at a glance. And again, the more you use multi-dimensional arrays, the more comfortable you'll get. These are a huge asset in PHP programming.

  53. Summary In this module, we covered what an array is and the difference between index and associative arrays. We learned a handful of built-in array functions, including array_key_exists, in_array, array_pop, array_push, count, sort, ksort, asort, and unset. We also learned how to loop through the contents of an array using a foreach loop. As an added bonus, we had a glance into the complex world of multi-dimensional arrays. This is one of the best assets of the PHP language, and when mastered will become a great addition to your PHP scripts. Let's head on over to the next module where we will learn about classes and objects.

  54. Classes & Objects Overview Object-oriented programming was added to PHP in version 4. In version 5, the object model was rewritten with more features, better performance, and now boasts a full object model. We will be focusing on object-oriented programming and the use of classes and objects. Just a quick overview of what we're going to learn in this module. We're going to learn what a class is, we're going to learn how to create a class and use a class, we're also going to learn how to access parts of the class, and we're going to learn about inheritance and visibility amongst the properties and methods inside of a class. And the very last thing we'll cover in this module is how to include PHP files inside of our script. Instead of going over a bunch of slides of what object-oriented programming is and what a class is, we're just going to jump right in and start programming classes with PHP. In the next clip, we're going to cover the basic structure of a class.

  55. Creating a Simple Class (Demo) In order to understand object-oriented programming, it's best just to start coding. In this clip, we are going to create a class structure. In PHP, all classes start out with the reserved name class. Let's go ahead and type out the word class. After the reserved word class, we then give our class a name, and in this case we are going to call our class Person. After the class name, we type the curly brackets. That's it. That is our class structure. The main idea about a class is that it's a container, something we can put stuff in and retrieve stuff from. So why do we use a class? A few ideas behind a class and why one would use it in their programming would be for code reuse, maintainability, and encapsulation, which means putting like data into a single component. So when creating a class, keep in mind of what items are related. For instance, the class we are creating is going to be all about an individual person. I wouldn't put stuff that dealt with movies or music in it, just stuff related to a person. As we continue creating our class, this concept will start to make more sense. In our next clip, we're going to create the object that uses this class.

  56. Creating an Object (Demo) Here I have my class. Remember, think of it as a container. Now I want to declare an instance of my class. There are a lot of new words I just said. So let's go ahead and type out our variable name. In this case, I'm going to name my variable name myObject. The reason why I'm calling it myObject is because when you declare a new instance of a class, that variable type is called an object. In order to remember that, I'm going to name my variable myObject. Let's go ahead and type that out. Just like all the other variables that we've learned in this course so far, we set it equal to. Now we want to declare a new instance of our class. Think of the term new instance of our class as a template of the class we are referring to. We can have an infinite number of Person templates or instances, which will have all of the contents of our class. In order to declare a new instance, we type the keyword new, and then we use the class name that we want to declare. And in this case, our class name is Person, so we type out Person. After the class name, we put an open and closed parenthesis, followed by our semicolon. Now that's it. That's how you declare an instance of a class, which is being saved to a variable of type object. So now we have an object, which has access to our class. We have laid the ground work for working with classes and objects in PHP. In the next clip, we will be adding properties, also known as variables, inside of our class.

  57. Creating Properties (Demo) Every class will have some type of variable that will be used throughout the class. These variables are called member variables, but there's also another term that we're going to use, which is called properties. All property variables start out with the word public, private, or protected. We will cover protected and private properties later in this module. For now, all of our properties are going to be declared as public. The idea of a public property or variable is that it can be accessed outside of this class through our object variable. It can also be accessed by other classes, which we will learn more about later in this module. Let's go ahead and give our Person class a few properties. When working with a class, we want to make sure that what we are defining in the class is associated with the class type. In our case, we have a Person class, and things that are associated with a person are name, age, height, birthday, and so on. With that in mind, let's create some properties for our Person class. Now properties are normally declared at the top of the class. Since our class is currently empty, we don't have to worry about that. I'm going to type the keyword public, and then I'm going to type a variable name. Since we are going to associate this property with our Person class, I'm going to have it be called firstName. Let's create another property. This will be declared as public, and let's give it a name of lastName. Let's create one last property. This one will be public as well, and the name will be yearBorn. So here I have three properties inside of my Person class. Now these properties can have an initial value, and since we don't have anything else declared inside of our Person class, let's go ahead and give each of these an initial value. I'm going to go ahead and paste in the content for these three properties. Now properties can have these default values, but the default value cannot be acted upon. For example, we couldn't have a mathematical equation for the year the person was born, nor can we have a string function processing the first name into all uppercase characters. So that's it for setting up our properties inside of our class. In the next clip, we are going to take our already declared object variable and use it to access or our newly created properties.

  58. Accessing Properties (Demo) Now that we have our class created with a few properties in it, let's go ahead and learn how to access those properties. We already have an object variable with an instance of our class. We're now going to take that object variable and use an object operator. The object operator is a dash followed by the greater-than sign. In order to access a property, we use our object variable, then we follow it up with a dash and a greater-than sign, and then the property name that we would like to access. Now the property name, which is also a variable inside of the class, is not used with the dollar sign syntax, so we just need to type the name of the property we want to access. In this case, we are going to type firstName. Remember, no dollar sign. Now that's how we access a property inside of the class, but this means nothing to us if we don't do something with it. The simplest thing we can do is print this property. In order to do that, we put an echo statement in front of it. Now we can run this. If you look in the output window, you can see that our first name has been printed out. Now these are public properties, which means we can also overwrite the value that is currently in it. So let's go ahead and write out our object variable, and now our object operator. Again, it's the dash and then greater-than sign. And now we can choose the property we would like to overwrite. Let's overwrite the firstName. So we have our object variable, our object operator, and our property name. Think of this as a variable where we can set a new value to it. In order to do that, we just say this is equal to and then the new value we would like to give this property. Let's go ahead and print out the firstName again. Now I'm going to go ahead and concat a new line at the end of our first print statement so we'll be able to see both of these on separate lines. Let's go ahead and run this. If you look in the output window, you can see our original first name value and the new first name value that we assigned outside of the class. That's it for accessing properties. In the next clip, we'll talk about constants and how to use them inside of a class.

  59. Creating Constants (Demo) In PHP, we can have constants that are accessible throughout the entire program, but we can also have constants that are just accessible inside of a class. This is an ideal approach if we want to keep our like things together inside of a single class, in this case all of our person needs. We already have our class Person with some defined properties. Let's go ahead and put our constant above these properties. In order to create a constant, we use the keyword const. That's C-O-N-S-T. Then we follow it with the constant's name. Now a constant name inside of a class still follows the naming conventions that are used for regular constants that are used throughout a PHP script. It will be all capitals, and any of the words will be separated by an underscore. Our constant will be the average life expectancy of a person. That makes for a really long constant name, so let's shorten it down to AVG_LIFE_SPAN. Now all constants have a value, so we need to give this one a value as well. I'm going to guess and say 79 is the average life expectancy of a person. Now unlike properties, a constant's value can be a mathematical equation, but there are limitations. It can't use any of the defined properties. For example, we couldn't use our yearBorn property in the equation. We have created a constant that is accessible only through this Person class. In our next clip, we're going to talk about how we can access this constant inside of our Person class.

  60. Accessing Constants (Demo) I'm going to show you two ways that we can access a constant that is inside of a class. I already have my Person class defined, and I have my object variable, which is an instance of the Person class. We can access the constant similarly, but not quite like we did with the properties. I'm going to print out the constant directly. So we're just going to type echo. Then I take the object variable and type that out. Now instead of using the object operator, we're going to use two colons. This is called the scope resolution operator. It has another term that the creators of the Zend Engine used. I'm not even going to attempt to pronounce it because it's in Hebrew, but the translation means double colon. So here we have our object variable, the double colon, and then we put the constant name that we wish to access. In this case, our constant is AVG_LIFE_SPAN. Let's go ahead and type that out. Now let's run this. If we look in the output window, you'll see our value being printed. The second way that we can access the constant is without even using the object variable. We can put the class name, the double colon, and then our constant name. So let's go ahead and modify our print statement. I'm going to remove the object variable, and in its place I'm going to type our class name, which is Person. Let's go ahead and run this. If you look in the output window, it's still showing the value of our constant. Later in this module, as our class gets more complex, we'll talk about how we can access our constants within our class. In the next clip, we're going to learn about creating methods.

  61. Creating Methods (Demo) In this clip, we're going to learn about adding methods to our class Person. Now methods are just functions that live inside of our class. We create these functions or methods to produce some sort of action for the class, which should be related to what our class is all about, in this case a person. Now methods are set the exact same way as a function. Let's go ahead and create a method right after our properties. We use the same keyword we use when creating a function. So we type function, and then give our method a name, and in this case we are going to call it getFirstName. Now this is an action regarding our person. We have a person, and we want to get that person's name. After the method name, we put our two parentheses and then our two curly brackets. Now that's it. That's exactly how we create a function outside of our class. But when we create a function inside of our class, we call it a method, so let's go ahead and create one more method inside of our class. Again, we start with the keyword function, and we are going to call this method setFirstName. It's an action pertaining to our person. Now this method is going to accept one parameter. Let's go ahead and put a temp variable here inside of our parentheses. Now don't forget to put our two curly brackets. Now all functions, like properties, can have a visibility of public, protected, or private. Remember that public methods and properties can be accessed outside of our class by an object variable and by other classes. We will be covering the protected and private visibility later in this module. By default, all methods are set to public even if the keyword is not present. Since we would like uniformity within our class, let's go ahead and add the keyword public before each of our methods. These methods are known as getters and setters because we are getting and setting our class properties, which we have not finished implementing quite yet, but in the next few clips we will. That's it for creating methods inside of a class. In the next clip, we're going to talk about the pseudo-variable this.

  62. $this (Demo) Here we have our class Person, and inside our class we have some properties and two methods. Now with these two methods, we want to be able to access the value and set the value of the class property firstName. In order to do this, we need to use the pseudo-variable this. Let's go ahead and demonstrate how this works, pun intended. Inside of our setFirstName we're going to type the word this, and it's typed just like a variable. Then we use our object operator, the dash followed by the greater-than sign, and then we use our property name exactly like we used it to access our property outside of the class. Now we can take this property and set it to our tempName that we are passing into this method. Now we've set up the setFirstName with our pseudo-variable this. Let's go ahead and set up our getFirstName with our pseudo-variable this. To get a person's first name means that we need to return a value. Just like in our function module, we use the keyword return. Let's go ahead and type return, and now we type our pseudo-variable this, followed by our object operator, and then our property firstName. That's the basic use of the pseudo-variable this. In the next clip, we're going to talk about how we access the methods inside of our class, and by doing so we will see our pseudo-variable this in action.

  63. Accessing Methods (Demo) We currently have our class, and inside of our class we have our constant, our properties, and our methods. We're going to take our object variable that we have already declared, and we are going to access our methods that are inside of our class. In order to access a method, we do it just like we access the properties. Right after we have declared an instance of our class, we are going to type our object variable, then our object operator, dash, and then the greater-than sign. Then we type our method name. In this case, we are going to type setFirstName. Because our setFirstName method takes a parameter, we are going to pass in a new value for the first name. Let's type in a new name. That's it. That's how we access a method inside of our class. Now we want to see what we have added inside of our method is actually working. In our last clip, we talked about the pseudo-variable this. Here we have it implemented. The pseudo-variable this refers to the present or current referencing object we are dealing with. In our setFirstName method, we have our new temp variable being saved to the firstName property. To see that this is actually occurring, we can print out the firstName property. Let's go ahead and type that out, echo, then our object variable, our object operator, followed by our property name, which is firstName. Now we can run this. In the output window, we can see that our first name has been replaced with the name we provided with the setFirstName method. We can also access our value through our getFirstName method. Let's go ahead and alter our echo statement. Instead of using the property, we can replace it with the getFirstName method. Now this method does not take any parameters, so we're done. Let's go ahead and run this. If we look in the output window, you can see that our new name that we set with our setFirstName method is appearing. That is how the pseudo-variable this works inside of these methods. That's it for accessing methods inside of our class. In our next clip, we're going to talk about constructors, which are basically a default method for a class.

  64. Constructors (Demo) Sometimes when we create a new instance of a class, we want some code to be executed immediately. We don't want to call an extra function after we have instantiated the class; we need that code to run immediately. Inside of the class, we can set a constructor. This constructor is a method that runs right when the class is instantiated. Let's add a constructor to our Person class. Since the constructor is a function or a method, we use the keyword function. The constructor has a specific name reserved in PHP. That name is __construct. Let's type that out. We have two underscores, then the shortened version of the word constructor, which is construct. We follow that with our two parentheses and our two curly brackets just like a regular function call. That's it. We have set up our constructor for our Person class. To demonstrate how this works, I'm going to put a simple print statement inside of my constructor. Let's go ahead and add echo, and then I'm just going to add a quick sentence. That's it. Now below we already have our object variable declared with an instance of our class. Now before when I would run this code nothing would happen because we didn't have any constructor implemented, but now when I call this Person class, the constructor will be called, and all the contents inside of our constructor will be executed. I don't have to add anything else to our object variable. We'll leave it as is. Now let's run this. If you look in the output window, you can see the print statement we put inside of the constructor. Let's go ahead and fix up our constructor to be a little bit more useful. We have three properties that have values set. Let's keep the properties, but remove the values and set the properties with those values inside of our constructor. Inside of our constructor I just type this, then my object operator, and then the firstName property. I'm going to set it to the same value that we had when it was the property default value. We have our property firstName receiving the value inside of the constructor instead of a default value outside as a property. The next two properties will be fixed with a little magic using cut and paste. Now we have all three properties being set inside of our constructor. To demonstrate this, we can either print out the property name, or we can call the getFirstName method. Let's use the getFirstName method to demonstrate that we are still receiving the value that we set inside of the constructor. Right under our object variable I'm going to type echo. Then I'm going to use my object variable and have it call the getFirstName method. Let's go ahead and run this. In the output window, you can see the first name that we set inside of the constructor. That's it for the constructor method. In our next clip, we are going to talk about passing initial values using our class declaration.

  65. Initial Parameter Passing (Demo) Just like with the functions and methods, we can pass in parameters into our constructor. In order to pass in parameters, we need to alter our constructor to accept those values. We also need to alter our class declaration object. First, let's alter our constructor. We have three properties that we are setting a default value inside of our constructor. Instead of giving them a default value, we are going to give them a value that is passed into the constructor. Just like any function or method, we need to give the value passed in a variable name. Inside of our parentheses in our constructor declaration, we need to type in three variables for the three values we would like to replace. My first variable will be for the first name, my second variable will be for the last name, and my last variable will be for the year the person was born. Let's go ahead and alter our properties so we can accept these new values that will be passed in. For the firstName, I will just delete this given value and replace it with the variable that is being passed in. I will do this for the other two properties. Now our constructor has been updated. What happens if we just declare our class, but don't pass in any values? We will throw an error. Let's go ahead and alter these variables so we can have a default value of an empty string. This way we can call our class, and if we don't want to set the values right then and there, we don't have to. The properties will be set to an empty string. Now our constructor is complete. We now need to alter the instance of our class down here. Inside of our parentheses here, we just need to pass in some values. Through the magic of copy and paste, here are our three values for first name, last name, and the year the person was born. Now we have set up our initial parameters and our initial values for our constructor. We also have our object variable set with the declaration of our class with our values being passed in. Now it's time to see all of this working together. We already have the method getFirstName being called from our previous example, so let's just run this script as is. In the output window, you can see the first name that was being passed through the instance of my class through the constructor is now being displayed. That's it for passing in initial parameters through the constructor when you have instantiated a new class. In the next clip, we are going to talk about inheritance.

  66. Inheritance (Demo) The simplest definition of inheritance is that it allows one class to inherit the methods and properties of another. Think of a child and a parent. The child inherits some of the features as their parents. This is the same principle. Here's the same code from our previous example, though I have made a few modifications. I have included a print statement inside of the constructor. I also created a new method called getFullName. This returns a concatenated version of the firstName and the lastName. You will also note that I included a print statement in this method as well. These two print statements will help us visualize inheritance as we work through the example. The last thing you probably noticed is the addition of a PHP-defined constant at the end of my print statements. PHP_EOL takes the place of our \n. The EOL stands for End of Line. In order for inheritance to work, we need another class where it can inherit the Person class. I have already created a class called Author. Let me go ahead and paste it here. Here's my Author class. I have one property called penName and one method called getPenName. In order for my class Author to inherit the class Person, I use the keyword extends. So right after my class Author name, I type the word extends followed by the class name I want to inherit. In this case, it will be the Person class. That is the only thing required to inherit another class. Now understanding how inheritance works on the class Author is a different story. Let's go ahead and create a newAuthor object. I'm going to set it equal to new Author. Notice that we haven't done anything with our object variable besides declaring the class. Now let's go ahead and run this. If you look in the output window, you will see the print statement from our constructor method in the Person class. Since the Author class does not have a constructor, the Author class is inheriting the Person class's constructor. Since we are accessing the Person Constructor, let's go ahead and pass in values when declaring the Author class. I'm going to go ahead and paste in my values. Now we are actually setting the properties in the Person class when we declare our Author class. These are being set in the Person Constructor. Let's go ahead and use our object variable and access our new method, getFullName inside of the Person class. Now remember, when you inherit a class, you inherit all of the properties and methods. We can go ahead and print out the getFullName using our author object variable. We just need to type echo, then the object variable followed by the getFullName method. Now let's run this. If you look in the output window, we still have our Constructor print statement, but now we have the print statement stating we are in the Person class inside of the getFullName method. After that, we see the contents of our full name being printed. Everything worked beautifully. Now what happens when the Author class has a method with the same name as a method in the Person class? Let's go ahead and copy the getFullName method from the Person class and paste it into the Author class. Now we just have to change one thing in our new method. That is our print statement. I'm going to replace the Person with Author. This way, when the method is printed, we know it's coming from the Author class and not the Person class. Now if you look at the rest of the method, you will see that it has the property FullName and the property lastName. The Author class doesn't have those properties, so the program will look inside of the Person class and see if there is a property firstName and property lastName. Now we know there are properties with these names in the Person class, which we are inheriting from, so it will return those values. Let's go ahead and run this. In the output window, you can see our three print statements. The first is from the constructor. The second is from the method we called, but notice it's coming from the Author class instead of the Person class. And lastly, you can see the actual full name of the author printed out. This is how inheritance works. If the child class has a method that is named exactly like a method in the parent class, the child's class's method, in this case from the Author class, will override the parent's method, in this case from the Person class. That's it for our basic example of inheritance. In the next clip, we're going to talk about properties and methods that have been set as protected.

  67. Protected Properties (Demo) Now that we understand inheritance, we now need to focus on the visibility of our individual properties and methods. Currently we have only used the keyword public when dealing with our methods and properties. Two new keywords that we can use for visibility are protected and private. These two keywords can be used on methods and properties. In this clip, we will cover the protected keyword. The idea behind the protected keyword means that the property or the method can only be accessed within the class itself. When you inherit a class, that class can also access those properties and methods that are protected. Now this is better demonstrated. Here I have my two classes from our previous example. The Author class is still inheriting the Person class. I have removed the print statements that were in the methods. I also changed the method name in the Author class to be getCompleteName instead of FullName. And if you look inside this method, you will see that I'm adding the penName onto the return statement. Now in order to protect any of these properties or methods, we just need to use the keyword protected instead of public. Inside of the Person class, we are going to change all of the properties to be protected. I'm going to replace the public keyword on each of these with the new keyword protected. I'm also going to make the getFullName protected as well. Lastly, inside of the Author class I'm going to change that property to protected. Now it's time to demonstrate what it means to be a protected property or method inside of a class. I already have my author object declared, and my initial parameters are being passed in. Let's go ahead and print out the penName property from our Author class. I'm going to type echo, then my object variable, and the property name penName. Let's run this. If you look in the output window, you are getting a fatal error. The error is saying we can't access a protected property, which resides in the Author class. We can't access any of the properties or methods directly if they are protected. Let's try this with the getFullName method from the Person class. Remember, it's protected. I'm going to swap out the penName for our method. Now we can run this. In the output window, you can see that we received another fatal error. This error though is stating that the protected method, getFullName, inside of the Person class cannot be called. Remember that protected properties and methods can only be accessed inside of a class or an inherited class. So the question is how can we access these properties and methods that are protected? In order to access a protected method or property, another method that is public needs to call it. We already have a public method, getCompleteName, which is grabbing three of our protected properties. Let's go ahead and call getCompleteName. I'm going to replace my protected getFullName method with my public method, getCompleteName. Now let's go ahead and run this. In the output window there is no error, and we have our return statement displayed, which called our protected properties. This is how protected visibility works. You can only access those properties and methods within the class itself. You can't access them outside of the class using the object variable. In the next clip, we are going to talk about using the private visibility with our properties and methods.

  68. Private Properties (Demo) There is another level of visibility when dealing with properties and methods within a class. That visibility level is private. We have already learned about the public and protected visibility. Now we are learning about the private properties and private method's visibility. I have the same code from the previous example. This time I have not made any modifications. I'm going to change all of the properties in both of my classes to be private. Currently, they are protected. In order to change from any type of visibility to private, you just need to use the keyword private; that's it. Let's take a moment and get all of these properties changed to be private. Now it's time to demonstrate how the private visibility works. I already have my object variable declared. I have my values being passed in through my class instance. Let's access the penName from the Author class object again. I'm going to type echo, then the object variable, then the property name penName. Let's run this. If you look in the output window, you will see that we have a fatal error stating we can't access a private property. All private properties and methods can only be accessed inside of the class where they are declared or set. In this case, the penName property can only be accessed inside of the Author class. Let's call the getCompleteName method from the Author class. Let's go ahead and run this. In the output window, we are seeing a notice that the properties are undefined. In this case, the properties are set to private, which are basically being treated as if they were never defined, even in the inherited class. Those private properties are firstName and lastName. We can fix this return statement inside of our getCompleteName. Let's swap out the two properties firstName and lastName and use the protected method getFullName. Now let's run this. In the output window, you will see the desired return statement from the getCompleteName method. Let's review why this works. Inside of our public method getCompleteName, we are calling a protected method getFullName. Protected methods and properties can be accessed inside of classes and inherited classes. Inside of the getFullName, it's returning two private properties. Now private properties and methods can only be accessed by the class where it's declared. Since the getFullName method resides in the Person class, this works. Our FullName is returned as expected. Now back to our getCompleteName method. After our FullName, we have a private property penName. This is also being accessed by class it was declared in, so it completes our return statement inside of our public method, which is accessible by our object variable. In our next clip, we are going to discuss static properties and methods.

  69. Static Properties & Methods (Demo) Now we are going to discuss the last type of property and method that we can have inside of a class. That type of property or method is static. A static property has to have a value set, and a static method has to be self-contained. To be self-contained means that it can't rely on any of the other class's properties or methods to accomplish its coding tasks. It can, however, rely on other static properties and methods. Let's go ahead and alter the code we have from our previous example. Inside of the Author class, I'm going to add a new property. It's going to be public, and it's going to be called centuryPopular. Now since static properties and methods need to be self-contained, it needs a value. I'm going to guess and just say that most classic authors were popular in the 19th century. Now to make this property static, I need to add the keyword static to the property right after the public keyword. Now that's the only thing you need to do to create a static property. Let's go ahead and make a new method call inside of our Author class. We will make this method static. Let's type this out starting with the public keyword. Then we type the static keyword followed by the function keyword. Now we add our method name. In this case, the method is going to be called getCenturyAuthorWasPopular. Now we just follow this up with our parentheses and our curly brackets. Now just remember when dealing with static properties and static methods, they must be self-contained. They can't rely on anything in the class except other static properties and methods. In the next clip, we are going to talk about how we access these static properties and methods.

  70. Scope Resolution Operator :: (Demo) Do you remember earlier in this module we talked about the double colon or scope resolution operator? We are going to use that scope resolution operator in this clip. Earlier we talked about accessing a constant value that was declared inside of our Person class. In this case, we are going to use the scope resolution operator to access our static properties and methods. Now we do not have to declare an instance of our class to access the static properties or methods, which means we don't have to use an object variable at all. We'll use the class name directly, followed by the scope resolution operator, and the name of the property or method we want to access. Let's print out our static property. Let's type echo. Now there's no need to declare an object variable. We just provide the class name that we want to get the static property from. In this case, it's Author followed by the double colon or scope resolution operator. Then we provide the static property name. Now when we are dealing with the object variable, we don't use the dollar sign, but when dealing with the static property, we do use the dollar sign. Let's type out our property name, but don't forget the dollar sign. That's all there is to accessing a public static property inside of our class. Let's run this and see it in action. In the output window, you can see that our value is printed. Now what about accessing our static method? This is called in the exact same way. We use our class name followed by the scope resolution operator. I'm going to replace the static property we have with our static method. Now that's it. That is how you call a static method inside of a class. Our method currently isn't returning any value, but we want it to return our static property. Normally this isn't an issue, but since our property is static, we have to change it up a bit. For regular properties inside of a class, we use the pseudo-variable this, but when it's a static property inside of a class, we use the term self. Now let's finish our method. I'm going to type return, followed by the keyword self, then the double colon because it's a static property, then the static property name. Just like accessing static properties outside of the class, we use the dollar sign inside of the class as well. Now that our method is set up, we can run our script. If you look in the output window, you can see the value of our static property. There is one caveat that I need to mention. When dealing with a static method or property from a parent class, instead of using the keyword self, we use the keyword parent. That's it for the scope resolution operator and the static keyword. In the next clip, we're going to talk about including files inside of a PHP script.

  71. Include File (Demo) PHP has the ability to include files inside of its scripts. The most commonly included file is a class. Conveniently, we have two classes we have been working with. I have separated out the two classes into separate files. I have separated out the Person class into a file named Person.php. I have also separated out the Author class into a file named Author.php. Common naming conventions indicate that you would name the file the same name as the class. In order to include a file inside of your script, you use the keyword include. At the top of my page, I'm going to type out the keyword include. Then in single or double quotes I type the name of the file I would like to include. We definitely need the Person class, so I'm going to type that out. That is all it takes to include a file. If you look at the object variable that is declared, you can see that I'm calling the Author class. Currently, I am only including the Person.php file. Now I need to include the Author.php file because it has my Author class in it. Again we type include followed by the file name, in this case Author.php. Using single or double quotes doesn't matter, but consistency is key. Now let's run this script. In the output window, you can see the value is being displayed. Sometimes we don't know if a file has been included or not, and we only want to have it included once in our script. In this case, we want to use the include_once keyword. We want to make sure that we are including one instance of our Author class. Now let's modify our include keyword to read include_once. When you include the same file twice, and the file contains a class or functions, PHP will throw an error indicating there is already an instance of that class, or that you can't re-declare a function. Using the include_once is ideal when dealing with files that contain classes or functions. Sometimes you might want to include a file with general code that isn't a class, nor has function calls. Using the include keyword would be beneficial in this instance since you can include that particular file as many times as you need. Include also provides the ability to include files from another directory, subfolder, or HTTP address. You just have to provide the proper path to that particular file. In the next clip, we're going to learn the difference between include and require.

  72. Require File (Demo) In the last clip, we learned about how we can include a file into our current script. There are two more keywords for including files into our scripts, require and require_once. These two sets of keywords work in the exact same way. They both are including a file from some other location, or they are including_once some other file from some other location. What happens when the file is not found? That is where these two sets of keywords differ. If I were to include a file that was not found in a particular location, the PHP script would throw an error, but then it would continue executing the rest of the clip. Let's see this in action. Right under my two include statements I'm going to type include, and then I'm going to give it some random file to include. Now I know that this file does not exist. Let's go ahead and run this and see what happens. In the output window, you will see two warnings. The first warning indicates that the script failed to open the file stating there was no file or directory. The second warning indicates it fails to open up for inclusion, but right under those two warnings you will see the output from our script. The rest of the file continues executing even though that include file was not found. What if I change the include keyword to be require? Now it's requiring that file, RandomClass, be included. Now let's run this. In the output window, we can see two errors just like with the include, but if you look at the second error it says fatal error. That is where the script terminates. This is the main difference between require and include. Include will continue to process the rest of the script where require will terminate at the point it can't find the necessary file.

  73. Summary In this module, we learned a lot about object-oriented programming. We learned about classes and objects and creating both. We covered accessing the methods, properties, and constants of a class. We also learned about extending a class and inheritance. Visibility of different methods and properties using public, protected, private, and static were discussed. And lastly, we learned how to include and require files inside of our script. Let's head on over to the next module where we will learn about operators and control structures.

  74. Operators & Control Structures Overview Now that we have covered functions, classes, and types, we can start getting into the fun type of coding with operators and control structures. An operator takes a value or multiple values and returns a new value. Think about adding two numbers together. The addition is an example of an arithmetic operator, this expression then yields anther number. We will be covering many different types of operators in this module. We will also be covering control structures. Control structures with the use of our operators allows us to control which blocks of code will be executed. Let's jump right into coding with arithmetic operators.

  75. Arithmetic Operators (Demo) In this clip, we're going to talk about arithmetic operators. Arithmetic operators are things that you would find on a calculator, such as, addition, subtraction, multiplication, and division. The arithmetic operators for simple math and php, are as follows, the plus sign is for addition, the dash or minus sign for subtraction, the asterisk for multiplication, and the forward slash for division. Here's an example of how to use addition, subtraction, multiplication, and division in a php script. I'm not going to cover the outputs of each of these, because I'd like the focus on the two new arithmetic operators that we'd like to learn. First is the modulus, the modulus returns the remainder of a number divided by another number, so let's go ahead and type a new echo here, and our first number is going to be 8, then we're going to type the module as sign, which is the percent sign, and then we're going to choose a number that we want to divide into 8 with. Let's go ahead and choose 3, just like our other examples here. Now 3 divides into 8, 2 times, which means that we'll have a remainder of 2, that's the modulus, it gives us the remainder of 1 number divided into another number. In this case, it's giving us the modulus of 3 divided into 8. So let's go ahead and run this, if you look in the output window, you'll see that our output is showing 2. 2 is the remainder of 3 divided into 8. Now you might be wondering, when would I ever use a modulus inside of a program, the perfect example of using a modulus inside of a script is to determine whether that number is odd or even. If you take the number and use a modulus 2, that will provide you with an easy way to determine if the number is odd or even. If it returns 1, it's odd, if it returns 0, it's even. The next arithmetic operator I'd like to discuss is the exponentiation operator. In simpler terms it's taking a number and taking it to the power of, so let's go ahead and comment out this line and make another echo statement. Now a simple exponentiation is a number squared. So let's go ahead and put 4, now the exponentiation operator is 2 asterisk signs so I'm just going to type 2 asterisks and then we'll put 2. So this equation is basically saying 4 squared. Let's go ahead and run this, and in the output window, you see that our output is 16, which is 4 squared. Now this can take any type of number for the exponentiation, so let's go ahead and leave 4 and change our 2 to be a larger number, let's go ahead and run that, and in the output window, there's our large number, that's 4 to the 8th power. That's it for arithmetic operators inside php, in our next clip, we're going to talk about incrementing and decrementing operators.

  76. Incrementing/Decrementing Operators (Demo) In this clip we're going to talk about incrementing and decrementing operators. Here I have a variable, and it's set to a value of 2, I'm also printing out my variable, so if I were to run this, our display window, would show 2, now an incrementing operator is 2 plus signs, added on either side of our variable. Now in between our variable with the value being set, and our printing of our variable, we're going to put in our incrementing operator, in order to use the incrementing operator, we type out or variable name, and then we add on either the left side of the variable or the right side of the variable our 2 plus signs. So let's go ahead and add this to the right side of the variable. Following the 2 plus signs, we then put a semicolon. The idea behind this is to add 1 to whatever the value is. So in this case our value's 2 using the double plus sign will now make that value 3. Let's go ahead and run this, and in the output window you can see that the value is 3. Now I can take these double plus signs and put them on the left side of the variable, let's go ahead and do that. Now let's go ahead and run this, now if you look in the output window our value is still 3, so what's the difference between having the double plus on the left side, or the double plus on the right side? When the double plus is on the left side it will add the value before it does anything else with that variable. In order to understand this, let's go ahead and alter our code here, I'm actually going to comment out our variable with the incrementing operator, and in our echo statement, I'm going to put the incrementing operator on the left hand side of the variable. Now when we run this, it will execute the incrementing operator first, and then it will print the variable, so let's go ahead and run this, now in the output window you'll see a 3, and that is an expected result. Let's go ahead and change our plus signs to be on the right side of the variable, so now what's going to happen, it will print the variable, and then it will increment the variable, so let's go ahead and run this, in the output window, you'll see that it's a 2, that's because it's printing the variable first, then it's executing the incrementing operator. Now all of these operations can also be done with the decrementing operator, which is the double dash, or 2 subtraction signs. So let's go ahead and remove these plus signs and put the double negatives, or the double dashes or the double subtractions to the left hand side of the variable. Let's go ahead and run this, in the output window, you'll see that our value has decreased by 1. That's it for the incrementing and decrementing operators. In our next clip, we're going to talk about the assignment operators.

  77. Assignment Operators (Demo) In this clip we're going to talk about the assignment operator, the idea behind the assignment operator, is the ability to eliminate the constant use of our seeing variable name, here's the code that I have. First I have a variable set to a value, and then my next line of code is my variable, and it's set to my variable plus 1. And then I'm printing out my variable. In our previous clip, we were able to simplify this type of an equation by using our variable and then adding the incremental operator, so this would have simplified to our variable name and then our 2 plus signs. Now this is great if we want to increment by 1, but what happens if we want to increment by 3? So let's go ahead and alter this line of code so we can use our arithmetic operator. The idea is that we want to add a value to our variable and still use our variable name. We're going to remove our variable, and we can remove our plus signs from our equation. So now we have our variable set equal to, and then the value that we want to add, in this case we're going to change it to a 3. Now in order to use our previous value of 5 and then save it to the exact same variable, we use the plus sign, right before the equal sign. So now our equation is our variable name, the plus sign and the equal signs, right next to each other, and then the value that we want to add to the variable, and in this case we're adding 3, now let's go ahead and run this. You'll see that our variable is printing out its value, which is 8. This works the exact same way for subtraction, multiplication, division, modulus, and exponentiation. For good measure, let's go ahead and do the exponentiation, so we're going to remove the plus sign, and then we're going to replace it with two asterisks. Let's go ahead and run this, and if you look in the output window, you'll see our result, that's it for the assignment operator, in our next clip we're going to talk about the string operator.

  78. String Operator (Demo) In this clip, we're going to talk about string operator, the string operator functions just like the assignment operator, except it deals with strings instead of mathematics. In this case we want to concate two words together, so in my code I have a variable, and I have it set to a value, in the second line I have the same variable name, and that's set equal to my same variable name with a concatenation of another string. Now the idea behind the string operator is so we don't have to use the variable a second time inside of the same line of code. Let's go ahead and delete our variable that's on the value side of the equation, now we have the same variable set with two different values. In order to concate the second value, we just add a period in front of the equal sign. The period is our concatenation for any type of string in any of the variables, we take that period, and put it in front of the equal sign, and now we have a string operator which concats strings together without having to repeat the variable inside of the value. So let's go ahead and run this, if you look in the output window, you'll see that our string has been concatenated together. That's it for the string operator, in our next clip we're going to talk about the comparison operators.

  79. Comparison Operators (Demo) In this clip, we're going to cover nine different comparison operators. Now we're going to start out with a var_dump function. You might remember that from a few modules ago, the var_dump dumps out information about a variable and in this case, we're having it dump out information about a Boolean value, whether it's true or false. This will make more sense as we go through the demos. So let's go ahead and type var_dump and then our two parenthesis, and our semicolon. Now inside of the parenthesis of our var_dump function, we're going to have a comparison, the idea behind the comparison operator, is to compare two different values, one value on the left side of the comparison operator, and another value on the right side of the comparison operators. So if I take the integer value 8 and I set it equal, equal to 8, I'm then comparing these two and asking, is 8 equal to 8? So let's go ahead and run this. Now in the output window, you'll see that the var_dump is dumping a Boolean value, and thee Boolean value is true. What that means is our comparison is returning true. 8 does equal 8, now that was the equal comparison operator. The next comparison operator we're going to discuss is the identical comparison operator. The identical comparison operator makes sure that the value is equal and the type. In order to test this comparison operator, we just need to alter the contents inside of our var_dump. The identical comparison operator is 3 equal signs, so we just need to add one more equal sign inside of here, so now we have, is 8 identical to 8? Let's go ahead and run this. In the output window, you'll see that we're returning a true value, when would this comparison value return false, that's when the type is not the same, so let's ahead and make one of these 8's a string instead of an integer. Now let's run this. Now in the output window you'll see that it's returning false. The string value, 8 is not identical to the integer value 8, even though there values are the same, their types are not. The next comparison operator is the not equal comparison operator, this comparison operator can be written two different ways. The first way is using the less than and greater than sign, let's go ahead and fix up our comparison inside of our var_dump function. I'm going to have it say 7 and then the, less than sign, and the, greater than sign, and then 6. This is basically asking, does 7 not equal 6, so let's go ahead and run this. In the output window you'll see that the value is returning true, 7 does not equal 6. Now the other way to write the not equal comparison operator is using the exclamation point and an equal sign. So let's go ahead and swap out this comparison operator with the other way to say, not equal. Now if we run this, we'll get the same value. If you look in the output window, you'll see that the value is true, 7 does not equal 6, now it doesn't matter which not equal comparison operator that you use, so long as you keep it consistent throughout your code. The next comparison operator is the, not identical comparison operator, just like the identical comparison operator, this compares the types of the value, as well as the value itself. Let's alter our current comparison that we have, instead of having an integer 6, I'm going to change this to a string 7, so now we have, is integer 7 not equal to string 7, now if we run this, if you look in the output window, you'll see that it's returning false. Since 7 is equal to 7, it just makes sense that 7 is not equal to 7, but what if we're trying to compare for that type, and that's where that not identical comparison operator comes into play. In order to change our not equal comparison operator to a not identical comparison operator, we add one more equal sign to the not equal comparison operator, so let's go ahead and add that now. Now our comparison is saying, does the type integer 7 not equal to the type string 7, now let's go ahead and run this. If you look in the output window, the values returning true, string 7 and integer 7 are not the same type. Though the values are the same, their types aren't, so this comparison holds true. The next comparison operator that we're going to discuss is the, greater than comparison operator. The greater than sign is also referred to as the angle bracket with the opening on the left hand side. When using the greater than comparison operator, you're asking if the left hand side of the comparison operator is greater than the right hand side, let's go ahead and alter our comparison inside of our var_dump function. I'm going to set each side to be 7, and then I'm going to use the greater than sign as my comparison. So this is asking, is 7 greater than 7? Now 7 is not greater than 7 so this should return false. Let's go ahead and run this. If you look in the output window, you'll see that it is returning false. 7 is not greater than 7. Now the next comparison operator is greater than or equal to, which builds upon the greater than comparison operator. Here our comparison is 7 greater than 7, if we add an equal sign, right after our greater than sign, we now are asking is 7 greater than or equal to 7. Now let's go ahead and run this, if you look in the output window, you'll see that it's returning true. 7 is greater than or equal to 7. The last two comparison operators are the less than comparison operator, and the less than or equal to comparison operator. Just like the greater than and greater than or equal to comparison operators, the less than comparison operator, compares each side and determines if the left hand side is less than the right hand side. So let's go ahead and alter our comparison operator in our var_dump function. We're going to change it to the less than sign, that is the angle bracket with the opening on the right hand side, now since we've already done a comparison with two of the same values, let's go ahead and change one of these values. I'm going to change one of the 7's to a 6. So now we have the question, is 7 less than 6. Let's go ahead and run this, in the output window, you can see the value is returning false. 7 is not less than 6, in order to change our less than comparison operator into less than or equal to, comparison operation, we just add the equal sign. Now the question this is asking, is 7 less than or equal to 6. Now let's go ahead and run this, and in the output window it returns false. 7 is not less than or equal to 6. That's it for these comparison operators, we do have one more comparison operator that we're going to discuss in the next clip and that's the spaceship comparison operator.

  80. Spaceship Operator (Demo) This next comparison operator combines the less than, the equal to, and the greater than comparison operators all together in one comparison operator, and that's called the spaceship. I'm guessing they call it the spaceship because it looks like a spaceship, so the idea is that we can compare all of those three items together in one expression. Let's go ahead and jump right in to creating this spaceship comparison operator. Now this is a little bit different than the other comparison operators that we've been working with. The other comparison operators returned a Boolean value, a true or false. In this comparison operator, we're going to get a -1, a 0, or a 1. Typically, when we print out a comparison operator result, we get an empty string or a 1, where 1 is true, and the empty string is false, in some instances, php also determines that 0 is false, but this particular comparison operator is special, we can not just say that 0 is false and 1 is true. Because it is returning three separate value, each of them meaning something different. So instead of using a var_dump to demonstrate our example, we're going to print out the result of our comparison operator. Let's go ahead and type out echo, and then we're going to type a 1 and then our spaceship operator, which is the less than sign, the equal sign, and then the greater than sign, and on the right hand sign we're going to put another 1. So here we're comparing if 1 is less than 1, if 1 is equal to 1, and if 1 is greater than 1, let's go ahead and run this, in the output window you'll see the value 0. 0 indicates that they are equal to each other. Now let's go ahead and change one of the 1's to be a different value, I'm just going to put a 2 in there. So now my comparison is 1 is it less than 2, is it equal to 2, or is it greater than 2, so let's go ahead and run this, now if you look at the output the result is -1. This means that the left hand side is less than the right hand side, and in our case 1 is less than 2 so the result is -1. Now let's go ahead and swap our values, instead of having a 1, our spaceship comparison operator, and then a 2, let's swap those values and have a 2, our spaceship comparison operator, and then a 1. Now let's go ahead and run this. If you look in the output window, our value being returned is a 1, that's because the value on the left hand side is greater than the value on the right hand side. So here's an easy way to remember this, if the left hand side is less than, it's a negative, think of the negative of being less, and if the left hand side is greater than, then it's a 1. That's it for the spaceship comparison operator. In our next clip we're going to discuss logical operators.

  81. Logical Operators (Demo) In our previous clips, we've talked about the comparison operators and how they return a true or false value, the idea behind the logical operator is to take one comparison expression and pair it up with another comparison expression. For the sake of simplicity, I've taken each of my comparison expressions and saved the results into a variable. I'm printing each of these variables out in a var_dump function. If I run this, each of these will return a true value, let's go ahead and do that. If you look in the output window, you'll see our results are two trues, printed for each of our comparison expressions. So the idea behind this logical operator, is to take each of these expressions and make a new expression out of them. Let's go ahead and type up another var_dump function call and inside of here, I'm going to type my variable, so let's go ahead and type our first variable. And now we need to put in a logical operator so in this case I'm going to type out the word, and, and then I'm going to put in m other variable. Now remember, my two variables are comparison, expression, results. And the idea is that we want to say, is my first comparison expression true, and is my second comparison expression true. So if both of my comparison expressions are true than my logical expression will return true, let's go ahead and run this. In the output window, you'll see our three results, two of them are our comparison expression results and their returning true. The last result is our logical expression and its returning true. And remember the results of our logical expression is a combination of our two comparison expressions. Now in this example we use the word, and. Php also has another way that you can write and, and that's two ampersand signs. The two ampersand signs means and in most programing languages, In php, it has a higher precedence then the actual word and, and it's typically used more often. Let's go ahead and change our and to be the double ampersand sign. We're going to stick with the double ampersand sign throughout the rest of our code. Now when using the logical operator we don't have to use our comparison expressions, we just need to be able to use a variable or statement that is conditional, meaning that there's a true or false value associated with it. So let's go ahead and change our two variables to be a true and a false. So now in our logical expression, it reads, is our first variable true, and is our second variable true. Now since one of our variables is false, this logical expression should return false. Let's go ahead and run this. If you look in the output window, you'll see that our expression is false, in order to save time of testing all the different combinations for the and logical operator, I've created a table so you can see what the particular results would be for condition 1 being true or false, and condition 2 for being true or false. You will notice a pattern that the only way that you can get a logical operator to be true is if both conditions are true. Everything else returns false for the logical operator expression. Now we're going to cover the, or, logical operator. Now just like the and, the or logical operator can be written two different ways. Let's go ahead and change our code to utilize the first way that you can write the, or logical operator. So the first way is to actually spell out the word, or, so let's go ahead and remove our double ampersand sign, and in its place I'm going to type the word, or. Here we have two conditions, one is true and one is false. Now when I use the or operator, it's going to return true because it just needs one of the conditions to return true so one can always be false and one can always be true, and the logical operator expression will return true. Let's go ahead and run this, in the output window you can see the result is true, it just needs one of the conditions to return true for the entire logical operator expression to return true. We've already covered one way, which you can express the or logical operator, the other way is using the pipe, now you might be wondering where is the pipe key on my keyboard, well, it's on the backwards slash key, which is located right above your enter on a _________ keyboard. Now for the or statement, we use two of these pipes, which we call a, double pipe, and that represents an or logical operator. Let's go ahead and replace our key word, or operator, with our double pipe, or operator. Now we can run our script. If you look in the output window, you'll see that are or logical operator expression is still returning true. Again, in order to save time in testing all of the possible combinations for the or logical operator, I have created a table so you can see what the particular results would be for condition one being true or false, and condition two being true or false. You'll notice a pattern that the only way in, or logical operator will return false is if both conditions are false, everything else will return true for the, or logical operator expression. The last logical operator that we're going to cover is the, not logical operator. The idea behind the not logical operator is it takes the result of a condition and returns the opposite, so if my condition returns true, the not operator will say it's false, if my condition return false, the not operator will say it's true. In order to use the, not logical operator, we will use an exclamation point in front of any of the conditions. Let's go ahead and remove our entire expression in our var_dump function and type out one of our variables. Let's go ahead and use the variable with the true value, in order to use the not logical operator, I use the exclamation point, right in front of the variable name. We know that this condition is true, but when we put the not logical operator in front of it, it now will return it to false. Let's go ahead and run this. If you look in the output window, you'll see that the return value for our not logical operator is false, it took a true condition and changed it to be false. Let's go ahead and change to our other variable, if our condition returns false, and we use the, not logical operator on it, it will then turn the value to true. Let's go ahead and run this. And if you look in the output window you'll see that our value is returning true. That's how you use the not logical operator. Most of the logical operators in programing are used in, if statement, and ___ loops. In our next clip, we're going to cover the if statement.

  82. If Statement (Demo) Now we're getting to the fun part of programing and that's the if statement. The if construct, or if statement, is one of the most important features in our php language. This allows for conditional executing of a code fragment or a segment. What does that mean? That means I can explicitly say, only execute this portion of the code if a certain condition is met. Let's go ahead and program an if statement. I already have two variables set up here. My first variable is an array, my second variable is giving me the count of the array elements, so my array has five elements, my count variable will be holding the value of five. Syntactically the, if statement is similar to a function call, we start out by typing, if, we give it to parenthesis, and then two curly brackets, inside of our parenthesis is where we put our conditional statement. In the last few clips we've covered the comparison operators and the logical operators, either of these would work extremely well inside of our if parenthesis. So I'm going to go ahead and just use my count variable, and I'm going to use my comparison operator of greater than, now we want to show that our authors variable has at least one element inside, if we put a 0 here, this will work, our conditional statement with our comparison operator states that the number of elements in our authors array need to be greater than 0 for this code segment or code block or be executed. Now we currently don't have a segment or block of code inside of our curly brackets that will be executed. Let's go ahead and fix that, for simplicity, we will just have a print statement using my trusty cut and paste, in my print statement, I am printing out how many elements are in my authors array. Now let's go ahead and run this, if you look in the output window, you'll see that our print statement is being executed. That's because we have more than 0 authors inside of our array of authors. What happens if our authors array has no authors in it? Let's go ahead and make another variable right underneath the author's variable. We're going to name it the exact same thing and instead of providing an array of element, we're going to go ahead and provide the empty brackets signifying that this is an empty array. Are empty authors array is now overriding our previously set value of our author's array, which means there is no need to comment out our previous authors array, now let's go ahead and run this. If you look in the output window, you'll notice that nothing printed, our block of code was never reached, that's because our condition was never met. When dealing with an, if statement, think of it as a yes/no question. In this case, I'm asking, is the count of authors inside of the author array greater than 0? If the answer is yes, then we execute the block of code inside the curly brackets. What if the answer's no to our question, while previously it just skips over that block of code and doesn't do anything in regards to that conditional statement. What if we want to execute a block of code if the answer is no. That's where the else comes in, so our, if statement, is already saying, if this is true execute this block of code, then we type in the word, else and then we give it another block of code that we would like to execute in its place. Let's go ahead and add an else to our, if statement. So right after the curly bracket we're going to type the word, else. Following the else, we put in two more curly brackets, now we have our, if/else statement set up. We have a block of code if the answer to our if statement is true, and now we need to put in a block of code if our if statement is false, or if the answer is no. For simplicity, we're just going to add another print statement inside of our else segment. I'm going to go ahead and copy and paste this, now we have our full if/else statement set up. Now let's go ahead and execute this. Remember our author's array has no elements inside of it. If you look in the output window you'll see our print statement from the else cause being displayed. That's it for the if/else statement, in the next clip we're going to cover the else/if statement, which is just an add on to our if/else statement here.

  83. Else If (Demo) The else/if statement is a combination of the if/else statement, the idea is that we have an if statement where a conditional expression is checked, and if it returns true or if the answer is yes, then that block of code is executed, but the idea is that we want to check another conditional expression, and the way that we do that is adding an else/if statement to our if/else statement. The wording gets a little confusing so let's go ahead and just type this information out. So here I have my if/else statement, I want to alter this and add an else/if statement to it, so right after the if statement, and the curly brackets, which holds my block of code, I'm going to type in the word, elseif, it's all one word with no spaces. Right after the elseif, I'm going to put in parenthesis, these parenthesis will hold another conditional expression. After this parenthesis, I'm going to put in my two curly brackets, so previously our if statement was saying, if there's a number of elements that's greater than 0 in our author's array, go ahead and print out the statement. The problem with the statement, it's assuming that there's two or more authors because the author word at the end of the statement is plural, but what happens if there's only one author in our author array? We want to be able to print out the statement so it says, author singular. Let's go ahead and take our print statement from the if statement and put it inside of our elseif statement. Now we need to alter our comparison expression inside of our if parenthesis, so instead of saying, is count greater than 0, we're going to say, is count equal to 1, so using our equal comparison operator, I'm going to swap out our greater than sign with two equal signs, and I'm going to replace my 0 with a 1. Now if there's only one element in my author's array, I want this to print out, there is one author. I don't need to concat the count onto it, because I already know it's only going to be one. So let's go ahead and alter our print statement so it reads there is one author. Now let's go ahead and add a conditional expression to the else/if parenthesis. We're going to start by typing our variable count, and then we're going to follow that with the greater than sign, now for this comparison, we want to make sure the author's array has more than one element inside of it. That means that we have to make sure there's at least two elements inside of our authors array for it to execute this block of code. So let's go ahead and put a 1 here, we're saying that the author's array count needs to be greater than 1. Now we don't need to alter the block of code that would be executed inside of our elseif statement. So we finally set up our elseif else statement, in simple terms it's basically asking a question, and if that question is no, it's then asking another question, and if that question is no, it's then going to execute the else block of code. Let's go ahead and comment out our empty authors array and now we're going to go ahead and run this. If you look in the output window you'll see our print statement is printing up the there's a total of five authors. So our elseif statement is working perfectly. Now let's go ahead and alter our author's array so that there's only one element inside of it. Now let's go ahead and run this, if you look in the output window, you'll see that it's printing that there's only one author, so we have successfully set up our if/else/if statement. Now we have added just one elseif clause to our if statement, but you can chain as many elseif statements together as needed to get the job done. In the next clip we're going to cover the switch statement.

  84. Switch Statement (Demo) In this clip we're going to create a switch statement, which is similar to a series of, if statements. We currently have our elseif statement from the previous clip, I have altered it a little bit, I have added the php_eol constant on all of the print statements. I have also commented out the code so we won't have any extra print statement in our display window. We are going to create a switch statement from this code. It's best to jump right in and start coding. The switch statement starts out with the key word, switch. We then follow that with a set of parenthesis. We follow that with our open and closed curly brackets. Inside of our parenthesis we provide an expression or variable that we want to compare to different values. In this case we want to compare the count variable, let's go ahead and type the count variable inside of our parenthesis. Now inside of the switch statement we have different cases, think of a case as a small if statement, such as, what if our count variables value is equal to 0? That would be a case, or if our count is equal to 1, that would be a different case, in order to create a case, we type the keyword case. After the keyword, we provide the value we wish to compare the count variable to. In this case, we want to compare our count to 0, so let's go ahead and type a 0 next to our case keyword. After that, we use a colon, this colon separates the comparison from the code that will be executed. No if our count it equal to 0, we want to print out a result, let's go ahead and copy our code from our else block from our if statement. Are key statement is saying that if there are no elements inside of the author array, print this statement. Let's create a second case in our switch statement, this time we're going to compare if our count value is equal to 1. We type the word case again, and this time we're going to put a 1 next to it, then we follow that 1 with a colon. When the switch statement is run it will check the value of the count variable and if it's a 1, meaning there is only 1 author in our author's array, it will run the code directly after our case statement. Let's go ahead and copy the print statement from our, if statement if there's only one author. Now we have our two case statements, these two case statements take care of our special scenarios when the total number of elements in our author's array is less than 2. Since there are only two special scenarios we need to create another case statement. This case statement will run a piece of code when there are two or more authors in our authors array. Now we can't make a case statement for every potential number that could be in our author's array count. That would be crazy! But what we can do is have a default case statement, this default case statement will run if no matches are found in our previous case statements. Since this is our default case, we treat it a little differently, instead of typing the keyword, case, we type the keyword default. Now normally all default cases are at the bottom of the switch statement, let's go ahead and keep with the standard and type our default after the last case statements block of code. Since we aren't comparing our default case with a specific value, we just type the colon, this allows for everything that doesn't match the two previous case statements to have some code executed, now after the colon, we need to provide some code for executing, let's just use the print statement from our if/else statement. Now that we have our switch statement all set up, let's go ahead and run it. If you look in the output window, our result is that the switch statement executed our default block of code. This worked perfectly since our array contains five authors, let's modify our author's variable to have 0 authors. Now let's run this and see what happens, in the output window you will see all of our print statements being displayed, this is not what we wanted. We just want the single print statement for the certain case it matches, in order to prevent this from happening, we need to put in a brake statement after each cases block of code. The brake statement indicates that we have found our match and we no longer need to be in the switch statement. Let's go ahead and add our break keyword after our blocks of code. So now we have our break keyword right before the next case statement, but what about the default case, technically, since the default case is at the end, we don't need to provide a break statement. There is nothing else that would be executed, let's go ahead and add that break statement anyway. It makes the switch statement more complete, now we can run this snippet of code again. If you look in the output window, you can see that our case statement 0 has been found and that the block of code for that case statement has been executed. Our switch statement expression can also be other variable types, such as a string. Now earlier in this module, I made the comment that the switch statement would work perfectly with the spaceship operator, with the magic of copy and paste, I have a switch statement all set up with a spaceship operator. Here's my switch statement, if you notice my expression it's the spaceship operator, remember the outcome can be either a 1, 0, or a -1, if you look at the case statements the comparison values are 1, 0, and -1. Each of the blocks of code has a print statement indicating what the outcome is. Let's run this for fun, if you look in the output window, we have our answer to whether 5 is less than, equal to, or greater than 7. That's it for the switch statement in php, in the next clip we're going to talk about the turnery operator, which is a shorthand version of the if/else statement.

  85. Ternary Operator (Demo) In this clip, we're going to talk about the turnery operator. The turnery operator takes a simple if/else statement and condenses it down to one line of code. Sometimes in your statement you'll have a tremendous amount of code. This is not an instance where you'd use the turnery operator. A perfect example of an if/else statement that could be replaced by the turnery operator, is our own if/else statement from a couple clips ago. I have copied that code from the if/else statement we used in that clip. Here's my author's variable with an array of authors. I also have the count variable which is the total number of authors in the author's array. I also have my if/else statement but you will notice I have commented it out. We're going to use this as a template as we create a new expression with our turnery operator. the turnery operator is two different symbols, the question mark and a colon. They're not used next to each other, the turnery operator has a certain format that we need to abide by, the format is as follows, an expression, followed by the question mark, followed by another expression, then the colon, and lastly another expression. Now that's a lot to take in, so let's jump right in to our example. When using the turnery operator you normally save the result to a variable. Let's go ahead and type out a new variable. We're going to set our variable equal to, then we're going to provide an expression that is evaluated to true or false, conveniently we have such an expression from our, if statement. Let's go ahead and copy and paste that next to our equal sign. After our first expression, we follow it up with a question mark, now we need to provide a result if our expression is true. I have modified the print statement inside of my, if block of code, I'm just going to paste it here. Now after our result when the expression is true, we need to provide the result when our expression is false. In order to separate the two results we type a colon and then follow it with the result to be returned when the expression is false. In our else block of code we have a print statement, but again, I want to minimize the amount of text in our turnery operator. In this case I will just type, no authors. We now have a completed Turnery expression, let's walk through this so we fully understand what is happening here. First we have our variable where the result will be saved, then we have an expression that will evaluate to true or false, remember our expression is like a question, there will be yes and no answer, if the answer is yes, or true, then the first result will be returned and if the answer to the question or expression is false, then the second result will be returned. Now the hardest part about the Turnery operator is remembering if the question mark goes first or if the colon goes first. If you remember that the first expression is a question, you can pretend that the question mark is the punctuation, kind of silly, but it works. In order to see the results of our operator, we just need to print out our variable. Now we can run this. If you look in the output window you will see that we're returning the author's total, because our count variable is greater than 0. Let's go ahead and change the comparison expression, we know there is 5 authors in our array, let's go ahead and change the 0 to 6. That way we will get our false result returned. Now we can run this, in the output window we have the desired outcome. That's it for the turnery operator, in the next clip we will learn about the Null Coalesce operator, which in some instances can simplify the Turnery operator even more.

  86. Null Coalesce Operator (Demo) Just like the Turnery operator condenses a simple if/else statement down to a single line of code, the Null Coalesce operator condenses a simple turnery expression into something similar. Here's the code from our turnery operator example, I have altered the actual comparison expression from our previous demo. My expression now just asks the question, is the count variable true, and what I mean by true, I'm asking, has the variable been set. If the count variable is valid, meaning that it has been set with the value, then the count variable will be returned. If the count variable has not been set with a value, then the else portion of the turnery expression is executed. Let's go ahead and run this, as is. If you look in the output window, you will see that the count variable does have a value, and it's being saved to the outcome variable, which in turn has been printed in our output statement. Now it's time to modify this with the Null Coalesce, all I need to do is remove the question mark, and the count variable, and the colon, so basically, all of the Turnery operator. In its place, I'm going to type two question marks, these two question marks represent the Null Coalesce operator, in plain English this is saying, is the count variable true, meaning it has been set, then return the count variable, if it's not, then return the result for the false outcome. The Null Coalesce only works if the expression is determining if the variable has been set. Let's go ahead and run this, in the output window we are still seeing the same result, this is a good thing because we have a value in our count variable, meaning it has been set, let's comment out the setting of the count variable. Now a variable in php that has not been set is an empty string, it return nothing, so our count variable is not set, now let's go ahead and run this. If you look in the output window, you'll see that we're displaying the default value of count unavailable. Since our count variable is not set, this is the exact outcome that we anticipated. This operator is great for testing variables that have not been set, which makes this an ideal operator to use when dealing with data from a web page form. The beauty of this Null Coalesce operator is that you can chain as many as the operators together as you want. For example, I can add another variable after my first set of question marks, now don't forget the Null Coalesce operator, which is the double question marks, now let's walk through this. This states, if my first variable is not set, then use the next value, but if that variable is also not set, then move onto the next value, in this case, it's the default value that we have set. That's it for the Null Coalesce operator, in the next clip we're going to use our newly learned operators with the while loop.

  87. While Loop (Demo) In this clip we're going to cover the while loop, we already covered the for each loop in the array module, the for each loop is mostly used to loop through all of the elements in an array, and executing some block of code. The while loop is similar to the for each loop, but instead of having a finite number of loops based on the elements in array, the while loop will continue executing the same block of code while a certain condition is met. Once that condition is no longer true, the while loop will cease looping around the block of code, and continue executing the rest of the script. The while loop is similar to, the for each loop in structure. In order to create a while loop we use the keyword while, after the keyword while we use the open and closed parenthesis, then we follow up with the open and closed curly brackets. That is the basic structure of the while loop. We currently don't have any condition in place so this won't work. Let's go ahead and add an expression, I'm going to create a variable that is set to true. Now in the parenthesis of my while loop, I'm going to put my variable there, now we have our condition. This while loop, basically says, while reading is fun is set to true, keep looping around our block of code. Now we have not provided any code inside of our curly brackets, so let's go ahead and add a simple print statement, through the power of copy and paste, here is my print statement. Now we have a complete while loop, there is a problem though with our while loop, let's go ahead and run it and see if we can determine what the issue is. If you look in the output window, you will see that we have what is called an infinite loop, our variable that we are using as our condition for looping is always set to true, there is no place in our code that we set it to false. Since this is always true, the while loop will always execute, thus causing an infinite loop. In order to prevent an infinite loop we need to be able to change our expression so that it's not true. In this case we would need to set our variable to false to have the while loop terminate, let's copy our original variable declaration and paste it inside of our while loop. Now let's change the true to be false, now we have an instance where our while loop will execute a finite number of times. In this case, it will only execute the block of code once, since our condition is changed in our block of code, let's go ahead and run this. If you look in the output window, you will see just one print statement as we intended. Let's change up our conditional expression, first I'm going to start by creating an initial variable and giving it a value of zero. Then I'm going to use that variable inside my while loop and then use the less than sign, and now I'm going to follow it by a number, something small, let's say five. Now I have my conditional expression, which states, loop through this block of code, while the value of I is less than 5. Now we don't want to cause an infinite loop, so let's go ahead and use the incrementing operator on our variable I. Now we can run this safely. If you look in the output window, you will see that the while loop has executed 5 times, that's it for the while loop. In our next clip we are going to follow a more complex loop, the for loop.

  88. For Loop (Demo) In this clip, we're going to cover the for loop, the idea is that we will transform our while loop into the for loop. Here's the code from our last while loop demo, let's walk through it real quick. First we declared a variable with an initial value, then we have our expression, which if it's true will iterate over the block of code inside of the curly brackets, to prevent an infinite loop, we have included a way to change the expression to be false, by altering our expression variable. In total, we have three lines of code to correctly create a working while loop. The for loop takes those three lines of code and condenses them down to one. The for loop, just like the for each and the while loop has the same basic structure, the main difference is inside of the parenthesis. Alright, so let's get started, first we change the while key word to be the keyword, four. Now inside of the parenthesis, the four loop can take three expression, conveniently we have three expression from our while loop that will work perfectly in our four loop parenthesis. The first expression inside of any four loop is executed once and only once at the beginning of the four loop. We have a variable that we set to 0 initially, that would be perfect for our first expression, let's go ahead and move that into our parenthesis. After our first expression we need to provide a semicolon, now the second expression in a for loop is evaluated an the beginning of each iteration. Our current comparison will work perfectly, as long as this expression is true the for loop block of code will be executed. Now after the second expression we also need to provide a semicolon. The third and last expression is executed at the end of each iteration, this means that all of the code in the for loop will be executed first, and then this third expression will be executed or evaluated. Normally, this will alter something in the second expression, now we already have an expression from our while loop, that will work as our third expression, and that is the incrementing I variable. Let's go ahead and put that in our parenthesis. Now after the third expression, we do not need a semicolon. In fact, if you put one, and error will be throw. So we already have some code left over from our while loop that is executed on each iteration, so we're going to leave that there, all we have to do is run this. If you look in the output window, you will see our print statement printed the five times that we intended it to be, so let's recap the for loop. First, it has the same structure as the while loop, and the four each loop, which is the keyword followed by parenthesis and then the curly brackets. Inside of the parenthesis, it takes up to three expressions, the first is the initial expression, this is only executed once at the beginning of the for loop, the second expression is executed at the beginning of each iteration. The second expression is also some type of conditional statement, or a comparison. As long as the second expression is true, the for loop will continue to execute its block of code. The third and final expression is executed at the end of each iteration, this normally will alter the conditional statement in some manor. Most notably the variable that is used in the conditional expression and in the initial declaration expression. That's it for the for loop, in our next clip we will cover the alternate syntax for our control structures.

  89. Alternate Syntax for Control Structures (Demo) Each of the control structures we have covered can be rewritten so we don't have to use the curly brackets. The first curly bracket is replaced with a colon, and the end or closing curly bracket is replaced with the word end followed by the control structure name. Here I have a few control structures I used in previous clips, let's alter these to use the alternative syntax. Let's start with the for loop, I delete the first curly bracket, or the opening curly bracket, and replace it with a colon. Now we move onto the closing curly bracket, I'm going to go ahead and delete that as well. Now each control structure has its own keyword ending. The for loops ending keyword is end for, now we just type it in place of our closing curly bracket, that's all there is to it. The alternative syntax is easy to use, let's go ahead and fix up the while loop to use the alternative syntax. I replace the opening curly bracket with a colon, now we replace the closing curly bracket with the keyword end while. Since we are on a roll, let's finish up with the if/else statement. First, let's replace the opening curly bracket with a colon, now let's replace the very last curly bracket with the keyword, end if, but now what do we do with the else, and the surrounding curly brackets. Well we delete each of the curly brackets and then place a colon after the else, that's it. Now we can run this with our new syntax in place. If you look in the output window you'll see that all of the control structures have executed as intended. You might be asking what's the purpose of this alternative syntax. Well it does make for a more simplified look, but the real benefit of this alternative syntax is when dealing with HTML code.

  90. Summary In this module we covered a lot of different operators, including arithmetic operators, the incrementing and decrementing operators, and assignment operators, the string operator, comparison operator, logical operators, the Turnery operator, and the new php seven operators, which include the spaceship and the Null Coalesce operator. We also covered a handful of control structures such as the if, if else, else if, the switch statement, the while loop, and the powerful for loop. Lastly, we discussed the shortened alternative syntax for our control structures which will come in handy when we start adding HTML to our code, or code to our HTML. In the next module we're going to learn about connecting to a database and accessing the data in it.

  91. Databases Overview Since version two, php has had the ability to connect to a database. Over time the functions and classes to access those databases has changed and evolved, some have even been deprecated. But the ability to connect to a database in any language opens the doors for endless opportunities. In this module, we are going to cover the databases that are accessible by php, we are then going to learn the difference between the two main methods to connect to a database, then we are going to jump right into setting up our current environment so we can access a database whether you're on Lenox or Windows. Once that is complete, we're going to use php to access out database and run queries against it. In the next clip we are going to learn about the databases that php can connect to.

  92. Possible Databases Currently, php has quite a variety of databases that it can connect to, I'm going to single out a few of those databases. First there's MongoDB, which is a document oriented database, then we have MS SQL, which is Microsoft's database. Then we have MySQL, which has been staple from php from the early days, then there's MariaDB, which is a compatible and comparable version to MySQL. Then there's the popular PostgreSQL, and also SQLite. There are a few more databases that php has the ability to connect with, but those drivers are managed by the php extension community library, or pickle. In our demos today, we are going to use MySQL as our database of choice. In the next clip, we're going to cover the two most popular ways to connect to a database using php.

  93. PDO vs. MySQli In order to connect to any database in php, you need a particular method. Php has two popular ways to connect to a database. The first way is using MySQLi and the second way is with the php data objects, or PDO. First let's list the features they each have in common. They each are object oriented, each supports character sets, both have the ability to perform multiple statements, and to create a query with server-side prepared statements. Each also has the ability to run stored procedures. Now let's go over the differences. MySQLi has the ability to be procedural instead of object oriented, this means that you can call all of the connections with a function call, instead of using an object variable. Secondly, using MySQLi, you have the ability to connect to the following databases, MySQL, MaxDB, and MariaDB. Now for the PDO differences. First PDO can create client side prepared statements, second, with PDO you can connect to all of the databases that were listed in the previous clip. This also includes all of the MySQL idatabases I just mentioned. Now that we know the differences, which one do we choose? Well PDO is newer, it was just released in version 5.3, now on the other hand, MySQLi has been around for a long time. Each of these perform the same tasks, and at the end of the day that's your ultimate goal, which will connect me to the database. The choice is up to you, do you feel like down the line you're going to be switching databases? Then I'd go with PDO, if you're pretty set on using a MySQL derivative database including MaxDB or MariaDB, then I would stick with MySQLi, but in the end it is, ultimately, your choice. In the next clip we're going to set up our Lenox environment with the database.

  94. Setting up MySQL in Linux (Demo) In this clip we're going to make sure we have access to the MySQL server, and we are going to install phpMyAdmin, which is a software tool to handle the administration of MySQL. All of the commands that we will execute are typed out here in the PowerPoint, that way you access to them in the course documents. Before we install anything, we need to make sure that our Ubuntu package lists are up to date. In order to do that we're going to run the sudo apt-get update command. Depending on the last time this command was executed, this might take a little bit of time. Go ahead and let that run until it's finished. Next we're going to make sure that we have MySQL installed on the server. If you are running version 12.04 or higher of Ubuntu then MySQL is already installed. If you're not sure if MySQL is installed on your version of Ubuntu, go ahead and type the following command. Mysql dash capital V, this will provide the version number of MySQL that you're running. If it doesn't print anything or if it says command not found, then you do not have MySQL installed. That means that you need to install MySQL and you can do that with the following command. Sudo apt-get install mysql-server, you will need to follow the prompts and when it asks you to enter in a password, go ahead and enter a password, even though this is a dev environment it's always good practice to have a password on your MySQL server. Now let's go ahead and install phpMyAdmin. We are going to run the following command, sudo apt-get install and then phpMyAdmin, all lowercase and all squished together. Now as this runs, you're going to be prompted several times, the first prompt will ask you if you want to select a server, and the answer is yes, we want to select a server and we want to select the apache server. In order to select that you need to hit the spacebar, and then we're going to hit Tab to get us to the OK button. Once that OK button is highlighted in red, go ahead and hit Enter. The next prompt talks about phpMyAdmin needing an initial database installed and configured before it can be used. Go ahead and select, Yes by hitting Enter. Another prompt will be displayed and it's asking for your server admin password. Now that's the admin password of the MySQL server. So go ahead and type that in, and once you're done with that, hit Tab to get to the OK button and hit Enter. The next prompt is asking us to create a password for the phpMyAdmin application itself. So go ahead and type in a password, then go ahead and hit Tab, to get to the OK button and hit Enter. Immediately following this prompt the next prompt will be a confirmation to the password that you just entered. So go ahead and type that in again, then hit Tab to get to the Okay button and hit Enter. Now we just need to let the installation finish, and once it finishes we're ready to access the phpMyAdmin in our browser. So go ahead and open up a browser, and you're going to want to type the following in the URL. Localhost/phpMyAdmin, you should see a login form in the middle of the page, go ahead and enter in the password that you setup during installation. After that you should be presented with the main page of phpMyAdmin. That's all there is to setting up our Ubuntu machine with MySQL and phpMyAdmin. In the next clip, we'll cover my SQL and phpMyAdmin installation on Windows.

  95. Setting up MySQL on Windows (Demo) Development on Ubuntu or any Lenox based machine with the apache webserver, php, and MySQL is normally referred to as the Lamp Stack, Lenox ,Apache, MySQL, php. There is a development environment that can be installed on Windows that acts like the standard Lamp Stack. Utilizing MySQL, Php, and the Apache webserver, except in a windows environment. The application is called XAMPP, this will install Apache, MariaDB, which is a drop in replacement for MySQL, and php. In order to install this, you'll need to download it from Apachefriends.org, I have already navigated to the site. Here are the versions of XAMPP that you can download, I'll be installing this on Windows, so I choose the windows option. I have already downloaded it. I am just going to go ahead and run it. This first prompt is just letting you know that there will be permission issues if you install this application in the program files folder. To avoid this we will be installing XAMPP off of the main C-Drive. Go ahead and click OK, and then click Next. Here are all the applications and services that will be installed when you install XAMPP. The main applications and services that you need to have installed are php, MySQL, and PhpMyAdmin, the rest are just extras. Go ahead and click Next, they already have the correct path for installation. I would suggest not changing this, click Next, at this time I do not want to learn about Bitnami, so I'm going to uncheck this box and I'm going to click Next. Then click Next again, now this will start the installation process, through the magic of editing, let's jump to the end of this process. Now our installation is complete. This is asking if we want to start the control panel, yes we do want to start this control panel right now. Click Finish, you may not realize it, but not service was started because we have a port issue with Apache. I currently have IIS on this machine, which has commandeered port 80. We need to update Apaches config file to use port 81. XAMPP has made this very easy to accomplish. I just click the config button and select to change to the Apache, HTTPD.compfile. Now let's go ahead and search for the word, port. Here is the listening port which is 80, I'm going to change this to 81. Now we need to change the server name, so I'm going to look for the keyword 80, which I guess I could have used for both searches. Here's the last place that we need to change port 80 to 81, now let's go ahead and save this file and we can close it. Now let's start the Apache service. Click Allow Access, now the Apache service name has a background color that is green. This means that it is running correctly. Now let's move on to getting the MySQL up and running. I just need to click on the Start button. Go ahead and click Allow Access, you will see that the service has turned green as well. Now we need to update our net beams to run off of the php from XAMPP, instead of the one we installed earlier in the course. I can close this control panel, and if you look at the icons in the lower right, you will see that XAMPP is still up and running, now we can open up NetBeams. I'm going to create a new project, and this is going to be a php application, and I'm going to click Next, I'm going to name my project something different, I will call is php fundamentals. Now what's awesome is that NetBeams has recognized that we have XAMPP installed and automatically filled out the source folder with the correct path. The path puts our project in the HT docs folder, this won't affect us in this module. So let's go ahead and lick next, and then we're going to go through the rest of these pretty quickly. So click next, click next, and then click finish. Now it's going to create our project. It automatically creates an index.php pile which has some HTML in it. I'm going to create a new file called connection. Now we need to change the location that NetBeams uses to execute php's scripts. I just need to click customize from this drop down. Now we need to make sure that our, run as, is set to be script run in command line, and that php interpreter or the .exc file should be located in the XAMPP folder. If it isn't, you'll need to select configure and navigate to the correct .exc file in the XAMPP folder. Now let's go ahead and run this empty script by hitting shift F6, to make sure our php is still working with NetBeams. And here's our output window, it works. That's it for setting up our windows environment, in the next clip we're going to use phpMyAdmin to create a database and table.

  96. Creating a Database and Table with phpMyAdmin (Demo) We are going to create a database and table using phpMyAdmin. As a php developer, phpMyAdmin will be your best friend forever. In Lenox you will navigate to localhost/phpMyAdmin and for those window users out there who installed XAMPP, we're going to need to fire up our XAMPP control panel, if XAMPP is already running, go ahead and double click on the little icon in the lower right hand corner. Now right across from the MySQL, you'll see a button called Admin, go ahead and click that. Now this normally would take you to the phpMyAdmin homepage, but unfortunately, right off the bat, you will see an error. This is because we changed our port number, so we need to add in port number 81. So right next to localhost in the URL I'm going to type a colon and 81 and hit Enter. One of two things might occur, we might see the login screen, and if you do you're going to enter your phpMyAdmin administration password, or the second scenario is it takes you right to the homepage of phpMyAdmin. In my case it took me right to the homepage of my PhpMyAdmin. So now our first order of business is to create a new user. My user name is going to be phpfundamentals. For the host name we're going to select Localhost, I'm going to use the same name for my password. This is not good practice, but since this is a tutorial I think it's going to be okay. Now for the privileges, I'm going to give this user all of the privileges since we are in a dev environment, and then we click Go. Now let's create a new database. We select the new link from the left hand navigation. I'm going to name mine phpfundamentals, I'm going to go ahead and leave this as coalition and click Create. Now we have our database. Next we need to create a table. Since we are just starting out we're going to keep things real basic, I'm going to name it, Authors and give it four fields or columns. Let's finish our table by filling out the column information. Our first column will be the standard ID field. We'll keep the type as integer, now we're going to select this to be our primary key and as a primary key we want to make sure it auto increments. Now our second column will be the first name and the type will be varchar and we're going to give it a length of 50, our third column will be last name, and this is similar to the first name, so we're going to give it a type of varchar and a length of 50. Now for the fourth and final column, this will be penname. Since this could be any combination of the first and last name, or something totally random, I'm going to set its type to be varchar with a length of 100. Now pen names can be null since some of the authors don't have one. In order to allow it to accept null as a value, we need to select the null check box. We have finished setting up our table, let's go ahead and click Save. Here is the final structure of our newly created table inside of our newly created database, which our new user is able to access. If you would like to learn more about phpMyAdmin or about creating relational databases, we have some great courses, here, on Pluralsight. In our next clip we are going to start coding again as we create a connection to our newly created database.

  97. Connecting to Database (Demo) We are finally ready to create our first database connection. Let's just jump right in, I currently have four variables set, these all pertain to my database I just setup. I have my username and password, my server location, and my database name. Now the database server location is set to localhost. This is typical when you're creating a site in development. As you start to go in production, you might be connecting a server that is not located on the same machine. That is just something to keep in mind, for now, localhost it is. We will be using the object oriented version of MySQLi. First we set an object variable. I'm just going to type my variable name, connection. This will be referred to as our connection, object, variable. Now this will be set equal to, and then we create an instance of the MySQLi class. That means we type the keyword, New, then we follow it with the class name, which just happens to be mysqli, all lowercase, then our open and close parenthesis, followed by our semicolon. The MySQLi class can take an initial six parameters, all of which are optional. We are going to pass in four of the six parameters. The first parameter we need to pass in the database server, I'm just going to type in the variable, the second parameter is our username, the third parameter is our password. And the fourth parameter that we will be passing in is our database name. Now the two parameters that we will not be utilizing which are optional are the port and socket parameters. We now have a completed connection string, if we run this, we won't see anything tangible happen. Let's go ahead and print out our connection object variable so we can see if anything was returned. We're going to use the Print R-function so we can see the contents of our connection object variable. Now let's go ahead and run this and see what happens. If you look in the output window, you will see our object variable of data. This has a lot of useful information but I want to direct your attention to these two properties. One is called, connect error no, and the other is, connect error. If you connection failed you would see these two properties populated. The connect error no, would have a number other than 0. This would be the error number provided by the MySQL database. Now the connect error would have a string equivalent to what the error number is referring to. Now with this knowledge, let's set up an, if statement that will exit us gracefully from our script. I just need to type if, and then my parenthesis and curly brackets, now let's put in our conditional statement. I'm going to type my connection object variable, then my object operator, now I'm going to follow it with the connect error no property. Remember error no is short for the error number. Now this, if statement says, if the connect error no value is set, meaning it is neither 0 nor an empty string, then we need to do something because the connection to the database failed. Now we need to set up a message informing us that the connection has failed. Conveniently, I have already crafted a print statement that I will paste here. If you look at the end of my statement, I have concatenated on a property, referenced from the connection object variable, just a reminder, this connect error gives a human readable sentence as to why the connection failed. Now if I were to run this and the connection actually failed, the script would continue to run because I have just a print statement inside of my if statement. When our connection fails, we want our script to stop altogether. In order to accomplish this, instead of having my message in a print statement, I'm going to put it inside of a function call, called exit. So let's go ahead and delete echo, and in its place I'm going to type exit and an opening parenthesis. Now I just need to put a closing parentheses before the semicolon, and that's it. Now this exit function will terminate a script and print out the message that we passed in as a parameter. Now we have properly created a connection string with a check in place in case we didn't connect the database properly. That's it for creating a connection string in php, now we can move on to closing our connection string in the next clip.

  98. Close Database Connection (Demo) In php all database connections are closed upon the completion of a script automatically, even though that occurs it is good practice to close your own database connections instead of relying on php. With that said, let's close the database connection we created in the previous clip. I have all of the code from the previous example except I've removed the print R statement, now closing a connection is quite simple. We include our closed connection after we have finished everything in regards to the database object. In our case, we've only created a connection so we would just include this after our if statement. So I'm going to go ahead and type my connection object variable, now I'm going to type the object operator, now after that I'm going to call the closed method, and that is actually the word closed. Following that, we put the open and closed parenthesis and the semicolon. That's all there is to closing a database connection. In the next clip, we're going to learn about querying the database.

  99. Executing a Query - Delete, Update, Insert (Demo) In this clip, we're going to query the database, I've added a few entries in database via phpMyAdmin. Here are some of the authors that I've added to the database. There are four basic types of queries that are commonly used in any given application, these queries are insert, update, select, and delete. In this clip we will cover all of these except select. That will be discussed later in this module. I'm not going to delve into the complexities of the SQL language, so all of the queries in this clip are relatively simple and should be easy to understand, especially for those beginners out there. Now let's try our hand at running a query in php. We are going to start out by deleting an entry in the database. Here I have my code from the previous demo. In order to perform any query you need two things. First, is the query itself, and second is the call to the query method from our MySQLi class object, fortunately enough, I'm going to provide the query call. Here it is, I have saved my query to a variable for simplicity, let's go over what the query is stating. The query states, delete an entry in the database from the table authors where the ID of the author is for. Now if we look in the author's table of our database, we can see what author is going to be deleted. Now that we have our query ready, we can create the call to actually run the query against the database. First, I type the connection object variable, then the object operator, then I use the query method, which is the name query. I follow that with our open and closed parenthesis and our semicolon. The query method can take two parameters, one is required and one is optional, we won't concern ourselves with the second optional parameter. The required parameter is a string, which contains our query. Let's go ahead and type our query variable as the parameter being passed into the method. That's it, now let's go ahead and run this. If you look in the output window, you won't see anything because we are not printing anything out to the screen. Instead, let's go over to phpMyAdmin and refresh our authors table. You will now see that we have one less author in our database, because we deleted an entry. Now let's go ahead and update one of our authors. I'm going to go ahead and comment out our delete query, now I already have a query to update one of the authors, here it is. Now this query is saying update an author, by setting the penname to this particular value, where the author ID is equal to two. Since our query variable is the same, we don't have to alter anything else, let's go ahead and run this. Let's go ahead and look at our table, in our database in phpMyAdmin, you will see the value has updated, now all that is left in the insert query. I'm going to go ahead and comment out our update query and paste in my insert query. The insert query is adding a new author to our table of authors, now I just need to run this script, now let's go over to phpMyAdmin and refresh our authors table. You will now see our newly inserted author. That's it for running a query against a database. In the next clip we're going to learn how to grab the ID of a newly inserted author.

  100. Grabbing Inserted Id (Demo) Sometimes after we insert a new record into the database we want to immediately grab the auto incremented value that was created. The auto incremented option is normally set on the ID of a column in a table, and that column is also designated as the primary key. In our case, we have done just that, our ID is set to auto increment and as the primary key. Normally, we would have to do a query to select the last inserted row and return the ID value. Php provides a quick shortcut. When a new record is inserted, the ID that was auto incremented on our primary key column is saved to the insert ID property in or connection object variable. Let's go ahead and print the ID of a newly inserted record. Remember, our ID is our primary key and has the auto increment option set. I currently have my code from the previous example, I have altered the insert data to be a new author. Now we know that this will insert this record upon execution, but we want to print out the ID. So after the query is executed, let's create a print statement. Now let's concat on the newly inserted ID. I type a period, this is a string operator, then I type the connection object variable, and the object operator, after that I type the class property, which is insert underscore ID. Now we can run this, if you look in the output window, you will see that our ID has been printed, let's go over to the phpMyAdmin and see the newly inserted record. If you notice, the ID is the same value that was displayed in our output window. That's it for accessing the ID from a newly created record. In the next clip we are going to grab records using the select statement.

  101. Select Data From Database (Demo) The select statement is a little different than the previous queries that we executed. The select query returns results and those results we need access to. Here is the code from the previous example, I have swapped the insert query with my select query. The select query is grabbing all of the authors in our table and sorting them by their first name, the first thing we need to do is have our query method saved to a variable, currently it is not. This variable will actually be a MySQLi result object. It is important to realize that this is a special kind of object. With this object we have access to a set of properties and methods for processing the results from the database. One of the properties that we're going to access is num_rows, this lets us know how many results have been returned from the query. The idea behind using the num_rows is that we don't want to process any of the results if there aren't any to process. Let's go ahead and create an, if statement to check if we have any results. I'm going to go ahead and set up my, if statement. Now let's go ahead and put in our conditional statement. I'm going to use the result object to access the num_rows property. This property is num_rows. I want to make sure that there is at least one result returned from our query, which is an equivalent to one row. So let's go ahead and have our num_rows be greater than 0. Now that we know that we have at least one result returned from our query, we can go ahead and process all of our results using a while loop. I'm just going to go ahead and set up the while loop. Now let's go back and add our conditional statement. In order to loop through each individual result, we need to save a result from a method to a variable. So let's go ahead and just type this out. I'm going to have a variable that I'm creating, I'm going to name it something very specific so we can understand what's going on here. Now I'm going to set this equal to, I'm going to use my result object and my object operator, I'm going to go ahead and use the fetch associative arrays method. Now this method call is a shortened version, I'm going to type in fetch, underscore, and then assoc and my open and close parenthesis. Now this method will return a single row of data as an associative array, and that single row of data will then be saved to our single row from query variable. Now inside of our associative array, each of the keys are column names. In order for you to see this, let's go ahead and have a print-R statement print out our associative array. Now let's go ahead and run this. If you look in the output window, you will see an associative array for each result from our query. Let's go ahead and recap our while loop. First we are looping through every returned result from our select query. For each row of data that is returned, we are storing the information to our tenth variable. Once our fetch associative array method has no more rows to loop through, our variable will be set to null. This null will cause the while loop to terminate or end. For each row we are printing out the data, now that we understand what is happening, we can spruce up our output in the while loop, conveniently, I have a print statement all ready to go. Look at my variable that I have concatenated into the sentence. Here is the temp array variable that is set in our while condition statement, and the key that I am using to access the data is a column name. I'm going to go ahead and comment out our print-R statement, now let's go ahead and run this. If you look in the output window, you will see that we have our information pleasantly displayed. Now there is just one last thing, just like the closing of the database connection, we need to free, or close the result object, right before the close method, let's go ahead and type our result object, and our object operator, then we're going to type the method, close. Now you can also use the method, free, now it doesn't matter which one you use as long as you're consistent throughout your code. That's all there is to using the select query and displaying the results. In the next clip, we're going to go over an example of using prepared statements.

  102. Prepared Statement Example In this clip, we'll cover an example of a prepared statement. Prepared statements allow for outside user input to safely be used inside of a query. The idea is to help prevent any type of SQL injection attacks. Let's look at the query first. I have changed it around a bit. I have removed the order by and put in a where clause. This where clause is basically stating that I want to return all of the authors, whose first name matches a specific word. This particular word used for our query would be coming from user input. Perhaps from a search box on your website. Now since we have not covered any web basics, I have created a variable with my search term in it. If we look closer to the select statement you will see a question mark. This question mark is a placeholder, it lets the script know that I will be sending the value later. Now in our previous example we used the method query. In a prepared statement or prepared query we used the method prepare. The method prepare lets php know that we will be sending our values later, we save the call to a variable just like the query method. This variable is now referred to as the statement object. In order to send our values later we use the method bind_param with our statement object. Now the bind_param method can take as many parameters that are needed to coincide with your placeholders or question marks in your query. There are only two required parameters for the bind_param method. The first is a type stream and the second is a value pertaining to the query. This means that you need to have at least one question mark that needs a value bound to it inside of your query. As a side note, all parameters that are passed in as values after your type string must be a variable. You are not able to pass in direct content, meaning that I can't remove this variable and type mark with quotes around it, the script will throw an error. Now back to our example of the bind_param, the very first parameter is a string equivalent to the value types you are passing in. For instance, I have an S in my bind_param first parameter, this indicates that my first value that I'm passing in will be a string. In order to grasp this fully here's another example, notice I am passing in three values, here is my type string, sdi, this means that my first parameter value is a string, my second parameter value is a decimal or floating point, and the third parameter value is an integer. There is one other type that is available for use in the bind_param and that is before blob. The order of your variable in bind_param should matchup with the order of your question marks in your query. If you're seeing unexpected results as you create more complex prepared queries or statements, I would check to make sure my values are in the correct order first. Now immediately following our bind_param method, we call the execute method using our statement object. This executes our query, it takes our parameters and inserts them into the query string at the appropriate locations. If I were executing a delete, update, or insert method, I would be finished. Since we are working with a select statement, we still have some work to do. After we execute our query, we now need to bind our results to some parameters, these will just be variables that coincide with the values our query is returning. Since we are returning the first name, last name, and penname, I've created variables with those particular names. Now we need to store the results to our bind result variables, and we do so by calling the store result method. Now for displaying our results, first we have a num_rows property that is accessible from our statement object. After that we can use the while loop, before we use the fetch associative method and saved it to a temp variable, but now we are able to simplify our while loop by calling the fetch method. There is no need to assign the result to a variable for processing. Now in our print statement, we can access the values with the same variables we used in our bind_result method. You will see that I have the first name, last name, and penname already set up. Now just like the result object, the statement object should be freed upon completion of the block of code that utilized it. In this case, I just swapped out the old object variable for the new one. Now unlike the result object the statement object can only be closed using the close method, where as the result object can be closed or freed by using the closed or free methods. Now let's go ahead and run this. In the output window you'll see that our results matched our search criteria, that's it for a basic example of a prepared statement. In the next clip we are going to examine the differences, with code, between database access with MySQLi and PDO.

  103. PDO Example In this clip I'm going to cover the PDO code equivalent based on the code example in our select data from the database clip. First we have the actual class call, the class call for PDO is PDO, in the MySQLi, you pass in your four variables, in the PDO connection you actually have to create a string to be passed in that contains your server and database name for the first parameter. The following two parameters you'll pass in the username and the password. The first parameter, which is a string indicates which database you're trying to access. In this example we're using the MySQL database, so we are passing in the MySQL keyword. This would change if you were using another database, such as Microsoft SQL or Postgres. Each database has its own keyword for use in the connection string. Continuing on, we see our query is the same, and the query method is the same. Now here is another difference, instead of calling a property for the number of rows, we use the row count method to grab the number of rows returned from our query. Now with PDO when we saved our query method call to a variable that variable now contains all of our returned results as an associative array. Using the for each loop, we loop through the elements from our query. In our example we are looping through each element and printing out the first name of the author. Once we are done with our result object and our connection, we set them to null, this is how PDO closes and frees up the database connection and result objects. Now let's go ahead and run this example. If you looking the output window, you will see the results are identical to those results we produced in the MySQLi select example. PDO is not harder nor more complex than learning MySQLi, you just need to become familiar with the nuances between the two.

  104. Summary In this module, we learned all of the databases that php can currently connect to, we learned the difference between PDO and MySQLi, we also set up our environment so we can access our database. We created our first database and table with phpMyAdmin, then we coded our connection to that database, which also included closing the connection and clearing our table, using insert, update, delete, and select. We also learned how to access the Id of a newly added record to the table, and we learned how to process the data returned from a select statement. Lastly, we saw our demo of MySQLi select converted to the php data objects or PDO code equivalent.

  105. Web Programming Overview Well, we have finally made it. We are finally discussing the main purpose why PHP was created, to create dynamic websites. In this module, we are going to cover the layout and structure of the website we will be working with. Then we will cover the two basic ways of accessing form data. Next will be form validation, and lastly, we will cover sessions. In the next clip we will make sure that we can view the website we will be working within a Linux environment.

  106. Setup Web Site Location - Linux (Demo) In this clip we are going to make sure our environment is set up to run our web application in the browser. The idea is that we have NetBeans run our project and it will open up in the browser. First things first, you will need to have a terminal open. As a reminder, all of the files for this course are residing in my home directory, which is, home/Pluralsight/Courses/PHPFundamentals. Here's the contents of that directory. We are working with the web, so let's go ahead and look inside the Web folder. I will discuss the layout and structure of the web application we are working with in a couple of clips, for now, these are our web application files. Now when working with a local web server in a Linux environment, the files are normally stored in /var/www/html, here's the contents of this folder. This index.html file is the default Apache page you will see when you access localhost in a browser. Let's go ahead and open up Firefox, and in the URL we're going to type localhost. Here is the default page of the Apache server, the same index.html page that we saw in the file structure. In order for our website to display, we either need to move all of the files into the var/www/html folder, or we can create a symlink. In our case, I think we'll use the symlink. With the symlink, we can keep our files where they are, but still access it through the localhost in the web browser. In order to make a symlink, we need to type sudo, which will run the command as administrator, then we type ln, for link, then a -s for symbolic. Now the first parameter that we add after the -s, is a path. This path is the location of our website folder and files, which resides in my user directory. This is the same path that we looked at earlier. The second parameter after the -s, is the path where we want our symlink to reside. In this case, we want it to reside in var/www/html. Now we need our website to be accessible off of the localhost, as if it were in its own directory, so after the html, we're going to put forward slash, and then we can put any folder name that we would like. Since phpfun is in PHPFundamentals, I'm going to name my sudo directory phpfun. Now we hit Enter, our symlink is now created. Let's go ahead and look at our Apache server HTML directory. Notice the blue color of our phpfun folder, this indicates we have a symlink. In order to see the details of the symlink and where it's pointing to, we can run the same command, but add the options -al. This will display a detailed view of the folder structure. Here's our symlink and the path it points to, which is our Web folder off of our home directory. Now in order to test out the URL, we can access our browser and type in phpfun after the localhost. Here is our website, it worked. Now we just need to set up NetBeans, so that when we run our project it will open our application up in a browser. My NetBeans is already open, so I'm going to navigate over there. In this drop-down at the top of NetBeans, I'm going to select Customize. Now this dialog box should look familiar since we have been here before. Under the Run As, we need to change the Script, run in command line, to be Local Web Site. Now that we've chosen Local Web Site, it's going to have a Project URL, which will automatically be populated with the project name right after the localhost. We need to alter this project URL path, instead of PHPFundamentals, we need it to read phpfun. Now we can click OK. Now when we run our project in NetBeans, it will open up directly into a browser. Here at the top menu, I'm going to select Run, and then I'm going to select Run Project from the drop-down list. Here's our website. We have finished setting up our Linux environment to run our web application from NetBeans.

  107. Setup Web Site Location - Windows (Demo) In this clip, we are going to make sure our environment is set up to run our web application in the browser. We want to be able to do this directly in NetBeans. Before we set up our NetBeans, we need to make sure we have completed our checklist. First, let's open up the XAMPP Control Panel. We need to make sure that we have started both the Apache and MySQL services. These should both be green. Next, we need to make sure our files are in the correct directory, all files that you would like accessible via the web browser need to reside in the htdocs folder inside of the xampp folder, which is off of the C drive. In module 8, we had created our project in NetBeans, which placed it in the htdocs folder for us. Now we just need to make sure NetBeans is set up to run our application in the browser. In NetBeans, we're going to select this drop-down, and select Customize. This pop-up dialog should look familiar as we have used it before. We need to change the value of Run As, it's currently set to Script, run in command line. We need to change it to, Local Web Site. After selecting this, it automatically populates the Project URL field. This is how/where we can access our website. Normally this would be fine and we could click OK and be on our way, unfortunately, this URL is inaccurate. Remember on our Windows machine, we have IIS running on port 80. That's the Microsoft web server. We had to set up our Apache server to be port 81, let's go ahead and alter this URL line to access port 81. In order to set this up, I just need to add a colon after localhost, followed by the number 81. Everything else should remain the same. Click OK, and now we are set to run our application and it appears in the web browser. To test this out, I just need to click the big green Play button here in NetBeans. Here's the web browser and it has opened up with our PHP web application. In the next clip, we're going to discuss the layout and structure of our website we will be using throughout the rest of the module.

  108. Web Site Structure and Layout (Demo) Here is the website we will be working with, it's a basic newsletter sign up form. It isn't much, and this is a rather scary photo of Charles Dickens, but for our learning requirements it will do the job. If I click the Submit button, it will take us to the results page, simple enough. Let's go ahead and look at the HTML code running the site and the structure of the files. Remember this is a PHP course, knowledge of HTML and CSS is implied. Here are the main input tags wrapped up in our basic form tag. Here's the page the form will end up on once the Submit button is clicked. We have a style sheet linked to the page, you can see that most of the styles are generic, but there are a few specific calls. I have put the image and the stylesheet in the assets folder. You'll notice that our drop-down list in empty, in the next clip we're going to populate the Author drop-down list with data from the database.

  109. Shorten Syntax with HTML (Demo) Here is the code for the main page of our website. In our last module, we created a database connection and queried the database, grabbing all of the authors. We are going to take that code and place it into our website. First, we need to create a new file in our assets folder, I'm going to call mine dbinfo.php, since this will hold our database password and connection. Now I'm going to paste the info into the file. I am separating this data from the main page, because in a normal website we would have multiple pages that would need a database connection. This allows it to be reusable, and if for some reason we need to change our password or database location, we only need to change one file instead of multiple files across the web application. In order to use this new file, we need to alter index.php to include it. Since this page needs this connection and data, we are going to use the keyword require. If the file isn't there, the page will fail to load. Now I'm going to paste the select query and query call here. Now that we have the groundwork finished, we can fill in the drop-down list with the favorite authors from the database. In the previous module, we learned how to loop through the results of a select query. We will use that knowledge and add our loop to the HTML code. Anytime you insert PHP into HTML, you need to use the opening php tags. This is the less than sign, followed by the question mark, followed by the word php. Now we type out our while loop. (Typing) Here we are setting each row result to the row variable. Earlier in this course, we learned about shortened syntax when dealing with loops and if statements. This shortened syntax will work with this while loop, even though we are encased in HTML. Let's remove the open curly bracket and replace it with a colon. Now let's remove the closed curly bracket and it replace it with the endwhile keyword. Personally, when working with HTML, I like the shortened syntax. In the end though it's your choice, but remember consistency is key. Now let's alter the option tag. First let's add the value attribute. In order to add a variable into HTML we can use the standard opening and closing php tags to declare PHP code, or we can use the shortened php opening tag, which I personally prefer for variables. For the shortened opening tag, we use the same less than sign and the question mark, but instead of writing php, we use the equal sign. Now we just add the normal closing tag. Now to add the variable, we do not have to have a space between the equal sign and the beginning of our variable. Now I just need to type the associative array variable, which is row, and then have a key of id. Now we just need to add the name of the author so it's visible in the drop-down list. Here is the code. I have two variables, one with the first_name and the other with the last_name. You'll notice by the associative key, each of these are using the shortened php opening tag syntax. Notice that I've put a space between the two variables. If this wasn't here, the first name and the last name would be right next to each other. Now for the moment of truth, let's go ahead and look at our web page. Here is our drop-down with the authors listed appropriately. Let's go ahead and view the source code. Go ahead and right-click, and then select View Page Source. You can now see the actual HTML of our drop-down list. Notice the value of each of the option tags, it's the ID from the database of each of the authors. Now that our form is complete, we can use it. In the next clip we will access the values from a submitted form, using the predefined get variable.

  110. $_GET (Demo) Here's the code from our previous clip, our form is set up so it goes to the final.php page upon submission. Our method for submission has been set to get. When using the get method in a form tag, the values will be displayed in the URL. Let's go ahead and submit the form with some values in it, and then I'm just going to click Submit. Notice the URL. All of the data we submitted is now located in the URL. As a side note, this is an insecure way of processing form data, but for this example we are covering this method so you can see how PHP handles the get method in a form submission. All data that is posted from a PHP form using the get method is stored in the predefined variable _get. This is an associative array. In order to see this in action, we are going to print out the predefined variable get. In order to do that we are going to use the print_r function. Now to access the predefined get variable, we type underscore and then the word GET, all capitalized. When printing out an array in a browser, the array will be displayed with all of the values on one line. This makes for reading the values a little hard. In order to print out an array so it looks pretty, we use the pre HTML tags. Pre stands for preformatted text. We will add the opening and closing tags around the print_r function. Now we are ready to submit the form again and see the data in the browser. Here's the contents of our form inside of the predefined get variable. As you can see, the predefined variable get is an associative array. All of the keys in the array are the names of the input that we set up in the HTML code. You might have noticed, we selected two centuries, yet only one is showing. In order for PHP to recognize more than one value in a checkbox scenario, we have to add square brackets to the name inside of the HTML. Let's go ahead and make that alteration. The square brackets indicate that an array value is needed. Let's resubmit the form. Now you can see the values that were selected are in an array saved to that particular key. Now in order to access an individual value, we would access it just like we access any values from an associative array. We use the name of the array, and then in square brackets we use the key name. I already have an example that I'm going to paste here. Let's go ahead and refresh our page. Since the data is in the URL, we should be able to see it in our results page. Here is our single value that we accessed from the get associative array. Since the get method when posting a form is insecure, we will switch our method to post in the next clip.

  111. $_POST (Demo) In order to process a form using the post method, we need to change the form method value. Let's go ahead and replace get with post. Now in the following page, let's replace our get variable with the post variable. Similar to the _GET variable, we type the word _POST, all in uppercase. Let's go ahead and run our project. Now let's go ahead and fill out some of the values in our form. All of the data will be passed to the next page using the post method, this means that all of the data is now stored in the predefined variable _POST. Let's go ahead and click Submit. If you look at the URL you will see that nothing was added, the post method does not add anything to the URL. We also have our printed out posted variable and all the data from our form submission is there. This is exactly what we were expecting. Since we are going to stay with the post method for our form submission, we can now add our posted data on the final page in the proper locations. Through the magic of cut and paste, I'm going to update the content. Here is all the data from our post variable, I have used the shortened syntax. Let's go ahead and refresh our page and see what happens. We now see our data from our submitted form displayed in the proper locations. When dealing with forms, we want to make sure that certain items are filled out. In the next clip, we're going to implement some form validation.

  112. Form Validation (Demo) Form validation is vital in any web application. The idea is that we what to make sure the user types appropriate data for the appropriate field. Perhaps we want to make sure an email address is in a proper format, or that a date field actually contains a date in a proper format. Validation can be as complex or as simple as you need it to be, it just depends on the requirements of your application. For our application we are going to check that the user has entered a value for the email address. We won't concern ourselves with the format at this time, we are just checking to make sure that there is data entered into the email field. Since it's ideal to display the validation errors on the form itself, we need to change the action of the form. Currently it's sending the user to the final.php page, we need to change that so the user is sent back to this page, where the form validation will occur. Let's change final.php to be index.php. Now to work on our validation, let's set up our if statement. Now we can add our conditional statement. We want to make sure that the data from our email input field is not empty. We will use the _POST variable and the email name as the key. Then we will set this to not equal an empty string. This states that if the email input does have a value, we want to send them onto the final.php page. In order to do this, we need to use a built-in PHP function that will redirect a user to any given page, in this case, our final.php page. This function is called header. The header takes one required parameter, which is a string value, and two optional parameters. Even though we are using the header function for a redirect to another page, it actually has more capabilities than that. We won't be covering those capabilities at this time, but just keep that in mind that the header function has more features than just the redirect that we will be using. Let's go ahead and type out the function, header. Let's pass in the required parameter. The parameter, which is a string, will contain the page we would like to go to. In this case we would like to go to the final.php page. In order to let the function know we want to be redirected to that page, we need to add a special word to our string value that is passed in. This special word is Location. We use a capital L and follow the word with a colon. After the colon, we provide the redirection URL that we would like to go to, and we already final.php set up. In our example our location is local, but we can redirect to a web page or another website by entering the entire URL. Now we need to finish our validation if the user hasn't filled out any content in the email input field. In our else clause, we are going to set a variable. The contents of this variable is a class name that is set up in our CSS file. When our div wrapper tag is set up with this CSS class name, it will turn the label and the input fields red, indicating that the field was not filled out. So now that we have this variable set, we need to actually put it in where we want the CSS class to show up if they did not fill out anything in the input field. Since we're only working with email validation, we're only going to add this variable to the wrapper around the email label and input field. I'm going to go ahead and use the shortened syntax and add my variable inside of the HTML attribute class. Now our page is all set with the form validation for the email field. We do have one slight issue, let's go ahead and access our page and see if we can spot the issue. Do you see the problem? Our validation is working right away, the user hasn't had the chance to fill out the form and we are already informing them that they have errors. Let's go ahead and wrap up our form validation with an if clause. Our conditional statement should check whether the form submission has been sent. We could check if the _POST variable has been set, but it's a predefined variable, which means it will always indicate that it has been set, whether it has any elements added to it or not. In order to get around that, we're going to check to see if that post variable has any elements by using the count function. Now we just need to make sure that there is at least one element in the predefined post variable, which means we need the greater than sign and we'll use the value of 0. Now let's test this out on our website. First we notice that our validation wasn't triggered right away, this is a good sign. Now let's add some content, but let's not add anything inside of the email input field. I'm just going to click Submit, now we've been redirected back to our same page, and now our email label and our input field are indicating that there was a problem with the validation. Now let's go ahead and add a value to our email input field. I'm going to click Submit, we have now been redirected to the final page. This is exactly what we wanted to happen, but do you notice anything different? Our data was not displayed, though we had filled out the form. When we redirected the page after the form submission, we lost all of our post data. Don't fret, there is a way to remedy this, we will need to implement sessions. Head on over to the next clip where we will discuss the session_start function.

  113. session_start() (Demo) Form validation provides a bit of a challenge to persistent data when you're reusing the form page to display validation errors. We need our post data to carry over to the next page. This will be accomplished using sessions. Sessions allow you to preserve data and access it across your entire website. This means that sessions are not just limited to forms and form data, though for our example we do happen to be preserving data from a form submission. In order to create a session in your PHP web application, you need to use the function session_start. This function takes an optional parameter, which is an array of options. For most web applications, and especially for our simple example, we won't need to worry about any of these options, so we don't need to pass in a parameter. Any page that you want to have access to the sessions will need this function call. We have two pages, let's go ahead and set up each with the session_start function. In order to use the function, we're going to type session_start and then the open and close parenthesis, and that's it. Let's go ahead and alter our other page. Now in the real world we wouldn't want to touch every single page to add the one function call, we would have a single file which would hold variables and includes to other files, and that file would be the only include on every page, that way, if we want to disable sessions, we would only have to change one file instead of multiple files. This will make more sense as we implement this. First, in my assets folder, I'm going to create a new filed called include.php. This file will be included on every single page in our web application. Inside of this file I'm going to add the session_start function call. Now I just need to update my two pages to include this file instead of having the function session_start on every page. (Typing) We now have a file that is included on every page. Things that would be needed on every page could be added inside of this file. In our case we are satisfied with just the session_start function call. That's it for starting a session in PHP, in the next clip we will cover the predefined variable _session.

  114. $_SESSION (Demo) PHP has a predefined variable called, session. This is used in conjunction with the session_start function. This variable is an associative array and is populated with any content that you would like to preserve from page to page as a user navigates your web application. In our case we want data to be preserved after the form submission has been validated and they are redirected to the final.php page. In order to use the session variable, we need to provide it with a key where we can access it in the final.php page. The best way to understand this is to jump right in and code it. Inside of my if statement I'm going to create a session variable right before the user is redirected. I type out the _SESSION, all uppercase, then I provide an associative key, this can be anything we want it to be, though it should be relevant to the data we are storing. In this case, we are just commenting that the form has been submitted. Now that we have our first session variable, we need to access it in the final.php file. I'm going to replace the _POST variable with our _SESSION variable. Now let's go ahead and submit our form. Don't forget to fill out the email address or we will be stopped for validation. Our redirect worked, and so did the utilization of the session variable. You can see the entire session array being displayed, and here is the session data we set before we were redirected. Now this particular value in our session variable isn't really helpful, what we need is the data from the form. Let's alter our code to pass along the form data in the session variable. Instead of stating the form was posted, let's give the key of something more meaningful, formPostData. Now since we want to capture all of the data that was posted, the easiest way would be to set this session key to be equal to the post predefined variable. Now all of our data will be accessible on the final.php page. Let's resubmit this form and see what happens. Here is our session variable, you will see that we have an array of data, which was our post data, and it's assigned to the formPostData key value in the session array. The next step is to get the data from the session variable to the correct positions in our HTML code. We could replace the post variable below with the sessions variable, but then we would also have to add the special key, which we saved the data to. This will make our HTML code a little bit more busy than we intended. A simpler way would be to save the session variable to a general variable for that page, let's go ahead and set this up. Now we have all of the form data stored in this one variable, which now is an associative array. In order for the data to be displayed in our HTML code, we need to replace the post predefined variable with our new variable name with a little magic of copy and paste. Now that we've updated our result page, let's go ahead and test out our site. Since we submitted our form via the session variable, all we need to do is refresh our result page. You can see that all of our entered data, from the form, is now displaying next to its label. In the next clip, we're going to learn how to destroy a session.

  115. session_destroy() (Demo) Here is our code from the previous clip, I have deleted our commented out code and I have removed the print_r statement from the final.php file. The beauty about PHP sessions is that they are always around and available. The bad thing about sessions is that they are always around and available. Let me demonstrate. Here in my final.php page it's filled out with our session data, I'm now going to navigate to the index.php page. No issue. Now I'm going to enter in the final.php page in the URL, bypassing the submission of the form. Do you see it? Our data is still there. This is not good because we didn't submit the form. The result page should not be accessible unless they access the page through the form submission. Let's rectify this situation. In our final.php file, let's put an if statement around our variable being populated by the session. Now our conditional statement should just check whether the session has been set, but not the session in general, we want to check a specific key value. To check if a variable is set, we use the function call isset. Isset takes one required parameter and an infinite number of optional parameters. No matter how many variables you pass into the isset function, the idea is that you're asking whether the variable or variables have been set. In our case we want to ask if the session variable formPostData has been set. If it has, then go ahead and process the rest of the page. If it hasn't been set, we don't want the user to see this page. In that case we need to add a header function call, which will redirect the user back to the form. Let's go ahead and add that now. Now we have one issue with our code, we have not destroyed or unset our session. That means that we will always be able to access the final page even though we would have only submitted the form once. Once we have saved our session data to our new variable, we should be able to unset the session variable. Now there are a few ways you can kill a session. I'm going to cover two of them. First you can destroy the entire session with the function call session_destroy. The function name is session_destroy, and then just open and closed parenthesis. Now this will clear all session data. This isn't the most ideal arrangement if you're using session data for other reasons in your web application. The other way to clear out session data is to use the function call unset. Unset is a standard function call used for any variable that has been set, and works well with session data. This will remove the data pertaining to a specific session key from the session variable. Let's go ahead and add this call after we have saved our session data to the variable. The function is unset, all one word, all lowercase, and for the parameter that we pass in, it's the variable we wish to unset. In this case, it's the same session variable with the key value, we checked if it was set to begin with inside of our if statement. Now our code is complete, let's go ahead and test it out. Here we are with our form. I'm going to go ahead and submit some new data. Here is the results page. All of the data is in the correct location and looks appropriate. If you recall the last time the page was refreshed, the data was preserved. Since then we've unset the session variable, let's go ahead and refresh it again and see what happens. Now that we've added the unset session, we have been redirected back to the form page. Let's try and type in our page name, final.php, in the URL and see what happens. Since our session isn't set anymore, we are redirected back to the form page, everything is working properly. That's it for destroying and unsetting sessions in PHP.

  116. Summary In this module we discussed our initial website layout, we talked about how data is posted when using post and get methods. We also talked about the post and get predefined variable that PHP uses to access form data. We implemented some form validation, and then we learned about sessions and how they work in PHP, including using the predefined variable session. You now have the knowledge to tackle more complex web applications, and with that, happy coding!