You are on page 1of 55

Introduction to PHP

Incorporating PHP Within HTML

 PHP document’s extension is .php


 When web browser encounters this .php file, it will passes it to the PHP processor
 PHP program is responsible for passing back a clean file suitable for display in browser
 It is HTML file
Calling the PHP Parser

 To trigger the PHP commands, you need


<?php
//Then write your php code, and finish by
?>
The Structure of PHP
Using Comments

 There are two ways in which you can add comments to your PHP code
 Single-line comments
<?php
//this is a comment
?>
 Multiple-line comments
<?php
/* This is a section
of multiple comments*/
?>
Basic Syntax

 PHP is very similar to C and Java


 Semicolons
 PHP commands end with semicolon $x += 10;
 The $ symbol
 You need to place $ in front of all variables
 This is to make parser faster (knowing variable)
<?php
$mycounter = 1;
$mystring = “Hello”;
$myarray = array(“One”, “Two”, “Three”);
?>
Understand Variables

 String variables
 The quotation marks indicate that is a string
 $username = “Fred Smith”;
 Numeric variables
 Variables contain numbers
 $count = 17; (integer)
 $count = 17.5; (floating point)
Arrays

 One dimensional arrays


 Used to store group of items
 $team = array(‘D’, ‘A’, ‘B’, ‘C’);
 Access array 4th item: $team[3];//’C’
 Two-dimensional array
 Example
<?php
$oxo = array(
array(‘x’, ‘’, ‘o’),
array(‘o’, ‘o’, ‘x’),
array(‘x’, ‘o’, ‘’));
?>
Variable Naming Rules

 When creating PHP variables, you must follow these four rules
 Variable names must start with a letter of the alphabet or the _ (underscore)
 Variable names can contain only characters: a-z, A-Z, 0-9, and _ (underscore)
 Variable names may not contain spaces.
 Variable names are case-sensitive
Activity: Variable declaration
Operators

 Operators are the mathematical, string, comparison, and logical commands


 E.g., plus, minus, times, and divide
 E.g., echo 6 + 2; //Output 8
Arithmetic operators
Activity: Arithmetic operators
Assignment operators
LHS = RHS;
LHS must be a variable
RHS is a value or an expression to be evaluated as a value
Comparison Operators
Activity: Comparison operators

FALSE: is null or nothing (e.g., empty string)


TRUE: is anything different from null or nothing (by default it is 1)
Logical Operators
Activity: Logical Operators
Activity: Logical Operators
String concatenation

 String concatenation uses the period (.) to append one to another


 E.g.,
 echo “have “ . $msgs . “ msgs.”;
 $bullentin .= $newflash;
String types

 PHP supports two types of strings that are denoted by the type of quotation mark that you
use
 If you wish to assign a literal string, preserving the exact contents, you should use single
quotation mark
 If you would like PHP to include the value of a variable inside string, you should use double
quotation mark
 Example:
 $count = 5;
 echo ‘There are $count msgs’; //There are $count msgs
 echo “There are $count msgs”;//There are 5 msgs
Escaping Characters

 Escaping Characters
 Special meanings that might be interpreted incorrectly
 E.g., $text = ‘My sister’s car is Ford’;//Error
 Must be: $text = ‘My sister\’s car is Ford’;
 There are characters like: \t, \n, \r
 The \ itself should be \\
Activity: String types and escaping
Variable Typing

 PHP is loosely typed language


 Variables do not have to be declared before they are used
 PHP always converts variables to the type required by their context when they are accessed
 Type can change based on the operation used on it
 Example:
<?php
$number = 12345 * 678; //$number is of int ype
echo substr($number, 3, 1); //$number is of string type
?>
Activity: Variable typing
Constants

 Constants are similar to variables (holding value) except that:


 Once you’ve defined it, its value is not changed
 E.g., Define the constant
 define(“ROOT_LOCATION”, “/usr/local/www”);
 E.g., Use the constant
 $directory = ROOT_LOCATION;
echo vs. print Commands

 Besides echo, there is another way to output text to browser, the print command
 print is the actual function that takes single parameter
 echo is a PHP language construct, it is faster than print since it is not a function and doesn’t return
value
 Example
 $b ? print “TRUE” : print “FALSE”; //correct
 $b ? echo “TRUE” : echo “FALSE”; //error
Functions

 Functions are used to separate out sections of code that perform a particular task
 Reusability (code once, use everywhere)
 For maintainability (changes in one place)
 For readability (clarity of your code)
 Example
<?php
function longdate($timestamp){
return date(“l F jS Y”, $timestamp);

}
echo longdate(time());
?>

You can have a reference to the complete list of date formats from here:
http://php.net/manual/en/function.date.php
Activity: Functions
Global variables
 To use global variables at the global scope inside a function we need to declare
these explicitly.
Superglobal Variables

 Starting from PHP 4.1.0, several predefined variables are available


 These are known as Superglobal variables
 They are provided by PHP environment
 Global within the program, accessible everywhere
 Contains lots of useful info about running program
 They are structured as associative arrays
Superglobal Variables
Superglobals and security

 We need to be cautious when using global variables


 They are used by hackers to break the website
 They could load $_POST, $_GET malicious code (e.g., Unix or MySQL command) that can
damage or display sensitive data if you naively access them
 PHP provides htmlentities function
 Converts all characters into HTML entities
 E.g., <and> are converted into &lt; and &gt; so they are rendered harmless
 E.g., $came_from = htmlentities($_SERVER[‘HTTP_REFERRER’]);
Conditionals
Conditionals

 Conditionals alter program flow


The if Statement

 The contents of the if condition can be any valid PHP expression


 Actions to take when if condition is TRUE are generally placed inside curly braces {}.
 You could ignore the braces if you have a single statement only (but this is not a good practice)
 Example
<?php
if($bank_balance < 100){
$money += 1000;
$bank_balance += $money;

}
?>
The if…else statement
The else Statement

 When the conditional is not TRUE, you may wish to do something else instead
 This is where else statement comes in
 Example
<?php
if($bank_balance < 100){
$money = 1000;
$bank_balance += $money;

}else{
$savings += 50;
$bank_balance -= 50;

}
?>
The elseif Statement

 Used to check different possibilities to occur based on sequence of conditions


 You can achieve this using elseif statement
<?php
if($bank_balance < 100){
$money +=1000;
$bank_balance += $money;

}elseif($bank_balance > 200){


$savings += 100;
$bank_balance -= 100;

}else{
$savings += 50;
$bank_balance -= 50;

}
?>
The switch Statement

 It is useful in cases one expression can have multiple values


<?php
switch($page){
case “Home”: echo “You selected Home”;
break;
case “About”: echo “You selected About”;
break;
case “News”: echo “You selected News”;
break;
default: echo “Unrecognized selection”;
break;
}
?>
Looping
Looping
while Loops

 if the condition is true, do the task inside the while loop


 Example
<?php
$count=0;
while($count < 10){
echo “$count times 12 is “ . $count*12 . “<br/>”;
$count++;

}
?>
do…while Loops

 The block of code is executed at least once before checking the condition
 Example
<?php
$count =1;
do{
echo “$count times 12 is “. $count * 12 . “<br/>”;
$count++;

}while($count < 10);


?>
for Loops

 It is very powerful since it combines abilities to


 setup variables as you enter the loop,
 test for conditions while iterating loops
 modify variables after each iteration
 Example
<?php
for ($count = 1; $count < 10; ++$count){
echo “$count times 12 is “ . $count * 12 . “<br/>”;

}
?>
break out of a loop

 Break statement will allow to break out of the loop when called
 Example:
<?php
for($i = 0; $i < 10; $i++){
if($i == 5){
break;

}
echo $i . “<br/>”;

}
?>
continue Statement

 Allowing PHP to skip everything after this statement in loop block and continue to the next
iteration
<?php
for($i = 0; $i < 10; $i++){
if($i == 5){
continue;

}
echo $i . “<br/>”;

}
?>
Implicit and Explicit Casting

 PHP is a loosely typed language


 It allows you to declare variable and its type simply by using it
 It automatically converts values from one type to another when required (implicit casting)
 How if you prefer to have explicit casting
 E.g., $a = 10; $b = 4; $c = $a/$b; by default will give you $c = 2.5.
 How if you would like to have 2 instead?
 We can use explicit casting $c = (int) ($a/$b);
PHP’s Cast Types
References

Nixon, R., 2014. Learning PHP, MySQL & JavaScript. 4th ed. Oreilly.

You might also like