Programming in PHP PHP is what is called a server side programming language. This means it resides on servers and allows web pages to communicate with the databases on these servers. It is used by sites like YouTube and Facebook to generate pages that look different for different users. It is a bit easier to get to grips with than Java for example. There are less rules and structures to abide by and you can get going pretty quickly.
They key thing about learning to program is that it is a transferable skill, the langauge is almost irrelevant. The skill of programming is about a way of thinking and using the tools at your disposal to solve problems and achieve goals. The programming constructs that you will learn in this course can be found in virtually all other programming languages. So it is safe to say, that if you learn to program, you should be able to move to any language you want as you have understood “how” to program.
Variables Every program needs to give the programmer access to variables. Variables are the storage space that the programmer can use to store values required in a program, for example a person’s name or age. Here is how a variable is declared and assigned a value:
$first_name = ‘Alfred’;
This means that the storage location called $first_name contains the word ‘Alfred’. If the programmer then references that storage location then the word ‘Alfred’ would be substituted for the variable name $name. For example:
print $first_name;
Would not see ‘$first_name’ printed to the screen, but instead the contents of that storage location, in this case ‘Alfred’. Naming Variables Most programming languages have conventions around how variables should be named. It goes without saying that the variable name should be meaningful and make sense to someone else who might look at your code, for example $age is more meaningful than $a.
It may be that you want to use more than one word to create a meaningful variable name. If this is the case then you have 2 options. Option 1: use capital letter to delimit your words e.g $firstName or $ageInDays Option 2: use an underscore as the delimiter e.g. $first_name or $age_in_days
PHP restricts the characters that can be used as part of a variable name to letters and numbers, so things like ‘!’ or ‘@’ are unacceptable characters to use as part of a variable name. Variable types PHP does not require the user to specify the variable type, it is able to work this out from what is stored inside. You will find that this flexibility does not exist in other languages. It is important to know what type of variable you are dealing with, as this will have implications as to what you can do with that variable. $firstName = ‘Alfred’; (PHP knows that this is what is called a String) $age = 56; (PHP knows that this is a numeric value) $activeClubMember = TRUE; (PHP recognises this as a Boolean value) Strings A string is a variable type that can store combinations of letters, numbers and symbols. So could be used to store things like an address or an ID number. The operations that you might perform on a string will be distinctly different from that of a number. For example you might ask PHP to capitalise the string, this operation would not work with a number and might generate an error. Similarly, you would be unlikely to try to add to strings in an arithmetic fashion, e.g. $name1 = ‘Alfred’; $name2 = ‘Batman’; $newName= $name1 + $name2; The outcome of this operation is nothing, PHP won’t do it. However, if we had the following scenario: $name1 = “12mup”; $num1 = 45; $newValue = $name1 + $num1; In this case, the value in $newValue is actually 57, PHP can see the 2 numbers at the beginning of our string and quietly converts them to be able to take part in the addition.
Concatenating Strings Concatenation is just another word for joining two or more items together to make a new longer item. It might be necessary to join strings and numbers together to store new values or print them to the screen. To do this we use the ‘.’ symbol: $name = ‘Alfred’; $age = 45; echo “Welcome to the Tax Calculator “.$name; (what would this print?) echo “You look very young for “.$age; (how about this?)
or $name = ‘Alfred’; $age = 45; $password = $name.$age; (would create the password Alfred45 ) String Functions A function groups a number of program statements into a unit and gives it a name, it is reusable i.e. it can be executed from as many different points in a program as required. There are a number of functions that can be performed using strings. ucfirst($String variable) – makes the first letter uppercase $var1 = ‘leona’; $var2 = ucfirst($var1); will store ‘Leona’ in var2
strtolower($string variable) – convert all letters to lowercase $var1 = ‘AlEsSANDRo’; $var2 = strtolower($var1); will store ‘alessandro’ in var2
strtoupper($string variable) – convert all letters to uppercase $var1 = ‘chris’; $var2 = strtoupper($var1); will store CHRIS in var2
trim($string variable) – remove any blanks at the beginning or end of the string $var1 = ‘ pedro ‘; $var2 = trim($var1); stores ‘pedro’ in var2
ucwords($string variable) – capitalises the first letter of each word $var1 = ‘hiu chun’; $var2 = ucwords($var1); stores Hiu Chun in var2
strlen($string variable) – gives the length of the string $var1 = ‘Hong Kong’; $var2 = strlen($var2); stores the number 9 in var2, the space is counted as well
These are not all of the possibilities, just some useful ones. If you need any other functions you can find them here http://php.net/manual/en/ref.strings.php
Numbers Some programming languages have different types of number variables, mostly related to precision. For example Java would require 2 different types of number variables to store 34 and 34.2. The whole number is termed an integer and the number with the fractional part of type double. There is no such need to do this in PHP. So this is acceptable: $a = 3; $b = 4; $a = $a/$b; (the answer to this is of course 0.75, which can be stored in $a)
Number Operators The usual numerical operators can be used with regard to numbers in PHP. $a = 4; $b = 5; $c = $a + $b; (adds 4 and 5) $d = $a - $b; (takes 5 away from 4) $e = $a/$b; (divides 4 by 5) $f = $a*$b; (multiplies 4 by 5) $g = $a % $b;
(called modulo division where the answer is the remainder of the division, in this case 4, because 4/5 is 0 remainder 4)
There are some shorthand ways to write the same operations, only if you are storing the answer in one of the variables involved: $a = 3; $b = 2; $a += $b; (add a and b together and store the answer in a) $a -= $b: (take b away from a and store the answer in a) $a /= $b; (divide a by b and store the answer in a) $a *= $b; (multiply a by b and store in a); $a %= $b; (modulo division of a by b, storing the answer in a)
Numbers can also be concatenated using the same method as strings. $a = 4; $b = 5; $c = $a.$b; (will store the number 45 in the variable c)
Boolean Types Boolean variables can only have 2 values, TRUE or FALSE. $check = TRUE; $check = FALSE; Boolean types can be used to make decisions in programs and are usually used in conjunction with comparisons and If statements. If Statement An ‘If’ statement is used to create different pathways in a program. To represent this visually we could use a flowchart.
In PHP an If statement is used as follows: If ( comparison to be made){ Code to be executed if comparison is true; } Else { Code to be executed if comparison is false; } Note the curly brackets enclosing the code to be executed. There might be any number of lines of code to be executed, it is not restricted to only one.
The previous example will only work if we only have two options to choose between. If we need three outcomes then we can use a variation of the ‘If’ statement. If (comparison) { Code if comparison is true; } Else if( second comparison) { Code if second comparison is true; } Else { Code if none of the comparisons are true; } We can continue to add ‘Else If’s and Else’s as necessary, depending on the number of outcomes we need. However, after a while, it gets difficult to keep track of the different clauses and conditions. A more readable structure to solve this problem is the ‘Switch’ statement. Switch The Switch structure is used to overcome the problem of choosing between many alternatives. Have a look at the example below: switch($state){ case "CA": $tax = 0.09; break; case "NY": $tax = 0.11; break; case "WA": $tax = 0.12; break; case "PA": $tax = 0.05; break; default: $tax = 0.10; }
In the switch($variable) part, we include the variable we want to check the value of, in this case a state. Each possibility then becomes a ‘case’. So if it is the ‘case’ that the state is ‘NY’ then the tax value is set to 0.11. The break statement is included so that as soon as one case is true, no others are checked, the program leaves the switch statement when one of the ‘cases’ becomes true. The default value is added in the possibility that none of the ‘cases’ are true, it is a bit like the Else section of the If structure. Comparisons In many programs it will necessary to compare values so that it can be decided what next course of action is. For example Lionel will provide different access rights to users who have a staff log-in compared to those who have student usernames. It is important at this point to talk about assigning a value and a potential pitfall of confusing this with a comparison. Assigning a value looks like this: $var1 = 23; (the value 23 is assigned to the variable var1, note that there is a single = sign used here) Comparing 2 values is similar but has one crucial difference $var1 == 23; (does $var1 equal 23?) this would normally be included alongside an if statement or even a while statement e.g. If($var1 == 23){ Code if true;} Else{ Code if false;}
Other operators that could be substituted for the == could be: === is identical(including type e.g. string) > greater than < less than >= greater than or equal to <= less than or equal to != not equal to <> Not equal to These comparisons generate a boolean value, a comparison can either be true or false.
Logical Operators: Complex Comparisons On occasion it will be necessary to build more complex conditions to be used in the ‘if’ statement or while loop. For example you may want to execute certain code when 2 values are true e.g $x==6 AND $y==7, but how would we code this? If($x==6 && $y==7){ …;}
Alternatively If($x==6 AND $y==7){ …;}
It may also be the case that you need to have 1 of 2 conditions be true rather than both. E.g If($x==6 OR $y==7){ Code to be executed if one of the conditions is true;} Else{…;}
An alternative for OR is ||.
It is possible to combine ANDs and ORs to build increasingly complex conditions to satisfy the needs of the code you are writing. If($city == “Springfield” AND ($state = “MA” OR $state= “VT”)){ This condition would be true if the city was equal to Springfield and the state was either MA or VT. It should also be pointed out that there is operator precedence. The symbols &&/|| are more important in terms of precedence than AND/OR so should not be mixed otherwise you could get unexpected results.
Repetition So far we have only written programs that we could call ‘linear’. They go through the instructions sequentially from start to finish. We need some way of ensuring repetition can take place and there are a couple of ways to do this. Conditional loop A conditional loop is one that uses a condition to decide whether to continue or not. While($userInput != “Stop”){ Code to be executed; } The loop above would continue until the variable $userInput became equal to stop. Therefore, as a programmer you cannot be sure how long this loop might repeat. It might be once it could be 100 time. The condition above is simple, but you can use the comparison and logical operators to build a condition that suits your requirements.
There is a variant of the while loop that behaves in a slightly different manner. Look at this example: Do{ Code to be executed; }while($userInput != “stop”);
This loop, like the previous example, continues to execute until the variable $userInput becomes equal to ‘stop’. However, there is a subtle difference here. The loop above will execute the code at least once every time. The comparison below explains this difference: Example 1 $num = 15; While($num <10){ //the condition is false, so the loop doesn’t get started Echo $num; //won’t get executed }
Example 2 $num = 15; Do{ Echo $num; //gets executed the first time through } while($num<10); // condition is false so loop stops
Fixed Loop The second type of loop is sometimes referred to as a fixed loop. This is because the programmer can control how many times it repeats. In most programming languages this is called a For loop, and PHP is no different. For($counter = 0; $counter < 10; $counter++){ Echo $counter; } This code would generate a list of numbers from 0-9.
Let’s break the parts of the ‘for statement’ down: $counter=0 – sets up a variable to be used to count the number of times the loop has been executed, initialise it to zero. $counter < 10 – the check to see whether the loop should continue. In this example the loop should stop when $counter is 10 or more e.g. it continues whilst $counter is less than 10. $counter++ - adding to the counter that takes place at the end of each time round the loop. In this example, only 1 is added each time but any value could be used.