Trinity CS Club Wiki
Advertisement

Overview[]

We are now going to begin the transition from HTML to a new language called PHP(Hypertext Preprocessor). In this lesson, I will explain many of the basics of PHP and some of its basic applications to HTML.

How to program in PHP[]

To program in PHP, we will be using HTML. Because there is such a strong link between the two of them, there is a tag for PHP in HTML. It is a very unique tag though. Here is how it works:

<!DOCTYPE html>
<html>
<body>

<?php 
//PHP CODE
?>   

</body>
</html>

All the PHP code is inside of a single a tag called php and there is a ? at the beginning and one at the end of the code. Unfortunately, most online compilers do not allow for people to use both HTML and PHP for some reason I don't know... So, we will need to use a different method of running our programs.

First, open a text editor. Something like notepad, notepad++, Microsoft Word, etc. will work. Then, you need to type in your html document like you would on the real-time editor we were using online. Next, save the document...

After this comes the nightmare which I always seem to forget... Basically, you need a server to run PHP code. It is possible to get to work on each individual computer but since many of you are using the computers in the computer lab, I decided just to get us a domain so that we can just upload stuff there to test it. I will explain how that all will work a little later when it becomes absolutely necessary. For now though,we are going to use another website that can run only the PHP code but not HTML with it. The website is: http://writecodeonline.com/php/

You can still write all your programs in the text editor and copy them to the online one but it isn't entirely necessary. Sorry for the confusion!!! The bright side is that we will definitely be using the text-editors later.

N.B. You can find Notepad++ here . It is only for windows but for Mac, sublime text which you can find here has similar functionality.

Basic Syntax []

PHP is a scripting language which means that it is capable of running code rather than the very static(unchanging) code of normal HTML. We use PHP for any kind of logic we want on a page. For example, what would we do if we wanted to the user to input a user-name and password and then wanted to check to see if it is valid? We had no means to do that now but with PHP we can. There are countless numbers of things you can do with PHP that add great depth to your websites. I am going to begin with the basics.

Very Basic Syntax[]

In PHP lines of code end with semicolons, except in a few cases which I will explain in a little while. In PHP, everything except for variables is not case-sensitive. I will explain what all those things are as we go along but for now just remember that.

Basic Output[]

In PHP there are two basic output methods: echo and print. They are basically the same and I cannot find a single difference between them. So feel free to choose whichever you like more :)

You can think of them as outputting HTML code--which you know how to do! Here are a few examples:

print "<h2>PHP!</h2>";
print "Hello world!<br>";
print "My name is Jacob";

N.B. On our online editor there are two options for how to ouput your PHP print and echo statements. Make sure to select "display as HTML"!

Variables[]

A very important difference between PHP and HTML is that PHP can have variables. Variables are similar to what they are in mathematics in that they hold a value. Here is an example of how they look:

$x=5;
$y=2.2;
$z=$x+$y;
$hello= "Hello World!";
echo $x-2;
echo "<br><b>$z</b><br>";
echo $hello;

The first thing you see is a lot of $ in that code. That is because every variable name must begin with a $ . Variable names can be about anything as long as they begin with that. You can also see that variables can hold just about anything. The variables in PHP can hold any type of number or string (along with a few other things too which you will see in a little while). Variables can also change types i.e. if you have one storing a string, you can later change it so that it holds an integer. The next thing you see are the echo statements. These echo statements show that you can can indeed output variables. The variables contained in quotation marks are no different than if you didn't have them but where the quotation marks come into play is that you can use HTML to edit how the outputted variable looks.

Experiment a bit so that you can get a feel for variables and output statements.

N.B. The br tag, if you don't remember, is effectively a new line character.

Data Types[]

In PHP, as with many other programming languages, there are a few key data types.

  • Integer: these are identical to how they are in math. i.e. 0,1, -1, 2, -2, ...
  • Float (sometimes called double): holds all real numbers in decimal form. i.e 1.2 , 2453576.9090909, etc.
  • Boolean: holds either a true or false. i.e. true, false  (that's it :) )
  • NULL: the null data type only has one value, null. null is basically the ultimate 0, false, etc. It has nothing else really going for it :) You won't use it very often, but I want you to be aware of it.
  • String: holds an (ordered) collection of characters. It can be about any length. i.e. "Hello!", " ", "", "12345", etc.
  • Array: arrays hold an (ordered) collection of any data type. I will get into this later.
  • Object: The term object has a much larger context, but for now just think of it as a user defined class

Arithmetic Operators[]

There are some operators in PHP that work for both integers and floats. They are +, -, *, /, ** which is the an exponential, and % which is the modulus i.e. a%b= the remainder when a is divided by b.

Strings[]

There are several useful functions that we can use with strings but I don't feel like copying what someone else has already written so check out this page for all he stuff you need to know about the strings.

I am holding off on arrays and objects until we learn a few more tools in PHP.

If Statements and Switch Statements[]

You can consider both of these as branching paths that a program can take depending on specified conditions.

Conditional and Logical Operators[]

In PHP there are a few conditional operators. They are == (equal to), != (not equal), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to). These operators will return a true or false value depending on the two variables they are comparing.

There are also some things called logical operators. The logical operators operate on true and false values. They are && (and), || (or), and ! (not). && and || are binary operators meaning they operate on two values where as ! is a unary operator meaning that it operates on one value. 

Just so you can get a feeling here are some tables:

p q p && q
T T T
T F F
F T F
F F


p

q

p || q

T

T

T

T

F

T

F

T

T

F

F

F


p

!p

T

F

F

T

If Statement[]

In PHP, the if statement is essential. It works with this syntax:

  if (CONDITITION)
     {
        
        DO THINGS
        
     }

The conditions rely on the conditional and logical operators that I just explained. Here is a more concrete example:

  $x=4;
  $y=4;
  $z=16;
  if ($x == $y && $z == $x**2)
     {
        echo "<h2> x and y are equal! </h2><br>";
        echo "z = x^2 ! <br>";
     }
  echo "x*y = ";
  echo ($x*$y);

As you can see, the syntax of things in PHP looks a lot different than what you are used to. The semicolons are only required on the lines inside the block statement (between the{}) and not on those lines themselves.

Else Statement[]

The other important part of if statements are the cases when it isn't true. You can have if statements alone, which if the condition is not true the compiler just skips it or you can have it so that if the condition is not satisfied, it moves on to a different set of code. That is known as an else statement. Here is the general syntax:

  if (CONDITITION)
     {
        
        DO THINGS
        
     }
  else
     {
         DO THINGS
     }

Here is a more concrete example:

  $x=4;
  $y=4;

  if ($x == $y)
     {
        echo "<h2> x and y are equal! </h2><br>";
     }

  else
     {
         echo "<h2> x and y are not equal! </h2><br>";
     }

What you can then do is have alternate things for it to do dependent on the situation!

Elseif Statement[]

The elseif statement is very similar to both the if and else statements (as you could probably tell from the name :) ).  Here is the general syntax:

  if (CONDITITION)
     {
        
        DO THINGS
        
     }
  elseif (A DIFFERENT CONDITION)
     {

       DO THINGS

     }
  else
     {
         DO THINGS
     }

And here is a concrete example:

$x=5.7;
$z=57.2283;
$a=3;
$b=74.5724;
if($x^2>$z && $a*$z<4)
  {
     echo "<h1> First qualities met</h1><br>";
  }
elseif($b-$z>101)
  {
     echo "<h1> Second quality met</h1><br>";
  }
else
  {
     print "<h1> Qualities not met :( </h1><br>";
  }

N.B. You can use the elseif statement as many times as you want.

Switch Statements[]

Switch statements are very similar to the if/else statements I just described. They act in a way similar to a chain of else-ifs. Here is the general idea for how they work:

$x=4;

switch($x)
{
     case 2:
        echo "X is two";
     case 7:
        echo "X is seven";
     case 10:
        echo "X is ten";
     case 4:
        echo "X is four";
      case 5:
        echo "X is five";
     default:
        echo "X isn't any of those...";
}

The general syntax is to choose a variable (in this case x) and then have cases for it. I chose some random ones. The numbers I used were the values I wanted to compare against. Similarly, I can use things like strings, decimals, etc. Then I have a default case which is what the switch statement chooses if none of the cases work.

Loops[]

One of the most important features of programming is being able to do a lot things quickly. We often want to things hundreds if not thousands of times. We don't want to write those steps over and over again so we use something to condense it. These are called loops and there are two types of them. While loops and For loops.

While Loops[]

While loops are pretty much a repeating if statement. They function basically the same way but they just continue to repeat as long as the condition is met. They look like this:

while (condition is true) {
    //Execute Code
}

There really isn't much new here but I will remind you that it is a good idea to a have terminating while loop. They can run forever and that is fine overall but programmers try to avoid it because it is inelegant.

For Loops[]

For loops work in practically the same way but we generally use them for tasks that we know how exactly many times we want them to run for. The general syntax is this:

for ($x = 0; $x < 10; $x++) {
    echo "The number is: $x <br>";
} 

We define a new variable x which is only available in the scope of the the for loop. Then we have a condition which in this case is less than 10. And lastly we have a part that basically changes the variable. In this case, I chose to use ++ (which is x=x+1). You can do whatever you want in there but ++ and -- are the usual ones people choose to use. After that, it functions in the same way as while loops.

Advertisement