Introduction to PHP

Useful Pointers

We will cover the following:

What is PHP?


Advantages of PHP


My First PHP Script


<?php
// Display greeting message
echo "Hello, world!";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>A Simple PHP File</title>
</head>
<body>
   <?php echo "Hello, world!"; ?>
</body>
</html>

Comments

<?php
// This is a single line comment
# This is also a single line comment
echo "Hello, world!";
?>

<?php
/*
This is a multiple line comment block
that spans across more than
one line
*/
echo "Hello, world!";
?>

Case Sensitivity in PHP

<?php
// Assign value to variable
$color = "blue";
 
// Try to print variable value
echo "The color of the sky is " . $color . "<br>";
echo "The color of the sky is " . $Color . "<br>"; // undefined
echo "The color of the sky is " . $COLOR . "<br>"; // undefined
?>
<?php
// Assign value to variable
$color = "blue";
 
// Get the type of a variable
echo gettype($color) . "<br>";
echo GETTYPE($color) . "<br>";  // as above
?>

Echo and Print Statements

<?php

print "Hello World!";

// Displaying HTML code
print "<h4>This is a simple heading.</h4>";
print "<h4 style='color: red;'>This is heading with style.</h4>";

// Defining variables
$txt = "Hello World!";
$num = 123456789;
$colors = array("Red", "Green", "Blue");

// Displaying variables with echo
echo $txt;
echo "<br>";
echo $num;
echo "<br>";
echo $colors[0];

// Displaying variables with print
print $txt;
print "<br>";
print $num;
print "<br>";
print $colors[0];
?>

Variables


<?php
// Declaring variables
$txt = "Hello World!";
$number = 10;
 
// Displaying variables value
echo $txt;  // Output: Hello World!
echo $number; // Output: 10
?>

Constants

<?php
// Defining constant
define("SITE_URL", "https://github.com/pytrain/web_prog");
 
// Using constant
echo 'Thank you for visiting - ' . SITE_URL;
?>

Data Types


Integer

<?php
$a = 123; // decimal number
var_dump($a);
echo "<br>";
 
$b = -123; // a negative number
var_dump($b);
echo "<br>";
 
$c = 0x1A; // hexadecimal number
var_dump($c);
echo "<br>";
 
$d = 0123; // octal number
var_dump($d);
?>

Floating Point Numbers or Doubles

<?php
$a = 1.234;
var_dump($a);
echo "<br>";
 
$b = 10.2e3;
var_dump($b);
echo "<br>";
 
$c = 4E-10;
var_dump($c);
?>

<>—<> Operations on Integers and Doubles

<?php
$x = 10;
$y = 4;
echo($x + $y); // 0utputs: 14
echo($x - $y); // 0utputs: 6
echo($x * $y); // 0utputs: 40
echo($x / $y); // 0utputs: 2.5
echo($x % $y); // 0utputs: 2
?>
<?php
// Round fractions up
echo ceil(4.2);    // 0utputs: 5
echo ceil(9.99);   // 0utputs: 10
echo ceil(-5.18);  // 0utputs: -5
 
// Round fractions down
echo floor(4.2);    // 0utputs: 4
echo floor(9.99);   // 0utputs: 9
echo floor(-5.18);  // 0utputs: -6
?>
<?php
$x = 10;
echo $x; // Outputs: 10
 
$x = 20;
$x += 30;
echo $x; // Outputs: 50
 
$x = 50;
$x -= 20;
?>
<?php
$x = 10;
echo ++$x; // Outputs: 11
echo $x;   // Outputs: 11
 
$x = 10;
echo $x++; // Outputs: 10
echo $x;   // Outputs: 11
 
$x = 10;
echo --$x; // Outputs: 9
echo $x;   // Outputs: 9
 
$x = 10;
echo $x--; // Outputs: 10
echo $x;   // Outputs: 9
?>

Strings

<?php
$a = 'Hello world!';
echo $a;
echo "<br>";
 
$b = "Hello world!";
echo $b;
echo "<br>";
 
$c = 'Stay here, I\'ll be back.';
echo $c;
?>

The escape-sequence replacements are:

<?php
$my_str = 'World';
echo "Hello, $my_str!<br>";      // Displays: Hello World!
echo 'Hello, $my_str!<br>';      // Displays: Hello, $my_str!
 
echo '<pre>Hello\tWorld!</pre>'; // Displays: Hello\tWorld!
echo "<pre>Hello\tWorld!</pre>"; // Displays: Hello   World!
echo 'I\'ll be back';            // Displays: I'll be back
?>

<>—<> String Manipulations

<?php
$my_str = 'Welcome to the Introductory Web Programming course';

// Count the number of charcaters
echo strlen($my_str);

// Count the number of words
echo str_word_count($my_str);

// Display replaced string
echo str_replace("course", "Course", $my_str);

// Display reversed string
echo strrev($my_str);
?>

<>—<> String Operators

Operator Description Example Result
. Concatenation $str1 . $str2 Concatenation of $str1 and $str2
.= Concatenation assignment $str1 .= $str2 Appends the $str2 to the $str1
<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!
 
$x .= $y;
echo $x; // Outputs: Hello World!
?>

Booleans

<?php
// Assign the value TRUE to a variable
$show_error = true;
var_dump($show_error);
?>

<>—<> Comparison Operators

<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z);  // Outputs: boolean true
var_dump($x === $z); // Outputs: boolean false
var_dump($x != $y);  // Outputs: boolean true
var_dump($x !== $z); // Outputs: boolean true
var_dump($x < $y);   // Outputs: boolean true
var_dump($x > $y);   // Outputs: boolean false
var_dump($x <= $y);  // Outputs: boolean true
var_dump($x >= $y);  // Outputs: boolean false
?>

Arrays

<>—<> Indexed Array

<?php
$colors = array("Red", "Green", "Blue");
var_dump($colors);
echo "<br>";
?>
<?php
$colors[0] = "Red"; 
$colors[1] = "Green"; 
$colors[2] = "Blue"; 
?>

<>—<> Associative Arrays

<?php
$color_codes = array(
    "Red" => "#ff0000",
    "Green" => "#00ff00",
    "Blue" => "#0000ff"
);
var_dump($color_codes);
?>
<?php
$color_codes["Red"] = "#ff0000"; 
$color_codes["Green"] = "#00ff00"; 
$color_codes["Blue"] = "#0000ff"; 
?>

<>—<> Multidimensional Arrays

<?php
// Define a multidimensional array
$contacts = array(
    array(
        "name" => "Peter Parker",
        "email" => "peterparker@mail.com",
    ),
    array(
        "name" => "Clark Kent",
        "email" => "clarkkent@mail.com",
    ),
    array(
        "name" => "Harry Potter",
        "email" => "harrypotter@mail.com",
    )
);
// Access nested value
echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
?>

<>—<> Viewing Array Structure and Values

<?php
// Define array
$cities = array("London", "Paris", "New York");
 
// Display the cities array
print_r($cities);

var_dump($cities);
?>

<>—<> Sorting Arrays

<?php
// Define array
$colors = array("Red", "Green", "Blue", "Yellow");
 
// Sorting and printing array
sort($colors);
print_r($colors);

rsort($colors);
print_r($colors);
?>
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
 
// Sorting array by value and print
asort($age);
print_r($age);
?>
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
 
// Sorting array by key and print
krsort($age);
print_r($age);
?>

<>—<> Array Operators

Operator Description Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y True if $x and $y have the same key/value pairs
=== Identity $x === $y True if $x and $y have the same key/value pairs
      in the same order and of the same types
!= Inequality $x != $y True if $x is not equal to $y
<> Inequality $x <> $y True if $x is not equal to $y
!== Non-identity $x !== $y True if $x is not identical to $y
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z);
var_dump($x == $y);   // Outputs: boolean false
var_dump($x === $y);  // Outputs: boolean false
var_dump($x != $y);   // Outputs: boolean true
var_dump($x <> $y);   // Outputs: boolean true
var_dump($x !== $y);  // Outputs: boolean true
?>

Objects

// Class definition
class greeting{
    // properties
    public $str = "Hello World!";
    
    // methods
    function show_greeting(){
        return $this->str;
    }
}
 
// Create object from class
$message = new greeting;
var_dump($message);
?>

Resources

<?php
// Open a file for reading
$handle = fopen("note.txt", "r");
var_dump($handle);
echo "<br>";
 
// Connect to MySQL database server with default setting
$link = mysql_connect("localhost", "root", "");
var_dump($link);
?>

NULL

<?php
$a = NULL;
var_dump($a);
echo "<br>";
 
$b = "Hello World!";
$b = NULL;
var_dump($b);
?>
$var1 = NULL;

// is not the same as
$var2 = ""

// $var1 has null value while $var2 indicates no value assigned to it.

Conditional Statements


if Statements

// Syntax

if(condition){
    // Code to be executed
}

if(condition){
    // Code to be executed if condition is true
} else{
    // Code to be executed if condition is false
}

if(condition1){
    // Code to be executed if condition1 is true
} elseif(condition2){
    // Code to be executed if the condition1 is false and condition2 is true
} else{
    // Code to be executed if both condition1 and condition2 are false
}
<?php
$d = date("D");
if($d == "Fri"){
    echo "Have a nice weekend!";
} elseif($d == "Sun"){
    echo "Have a nice Sunday!";
} else{
    echo "Have a nice day!";
}
?>

The Ternary Operator

condition ? value1 : value2;

<?php
if($age < 18){
    echo 'Child'; // Display Child if age is less than 18
} else{
    echo 'Adult'; // Display Adult if age is greater than or equal to 18
}
?>

\\ Using the ternary operator
<?php echo ($age < 18) ? 'Child' : 'Adult'; ?>

Switch…Case Statements

// Syntax
switch(n){
    case label1:
        // Code to be executed if n=label1
        break;
    case label2:
        // Code to be executed if n=label2
        break;
    ...
    default:
        // Code to be executed if n is different from all labels
}
<?php
$today = date("D");
switch($today){
    case "Mon":
        echo "Today is Monday. Clean your house.";
        break;
    case "Tue":
        echo "Today is Tuesday. Buy some food.";
        break;
    case "Wed":
        echo "Today is Wednesday. Visit a doctor.";
        break;
    case "Thu":
        echo "Today is Thursday. Repair your car.";
        break;
    case "Fri":
        echo "Today is Friday. Party tonight.";
        break;
    case "Sat":
        echo "Today is Saturday. Its movie time.";
        break;
    case "Sun":
        echo "Today is Sunday. Do some rest.";
        break;
    default:
        echo "No information available for that day.";
        break;
}
?>

Loops


PHP supports four different types of loops.

The “while” Loop

// Syntax
while(condition){
    // Code to be executed
}
// An example
<?php
$i = 1;
while($i <= 3){
    $i++;
    echo "The number is " . $i . "<br>";
}
?>

The “do-while” Loop

// Syntax
do{
    // Code to be executed
}
while(condition);
<?php
$i = 1;
do{
    $i++;
    echo "The number is " . $i . "<br>";
}
while($i <= 3);
?>

The “for” Loop

// Syntax
for(initialization; condition; increment){
    // Code to be executed
}
// An example
<?php
for($i=1; $i<=3; $i++){
    echo "The number is " . $i . "<br>";
}
?>

“foreach” Loop

// Syntax
foreach($array as $value){
    // Code to be executed
}

foreach($array as $key => $value){
    // Code to be executed
}
// Example
<?php
$colors = array("Red", "Green", "Blue");
 
// Loop through colors array
foreach($colors as $value){
    echo $value . "<br>";
}
?>
// Another example
<?php
$superhero = array(
    "name" => "Peter Parker",
    "email" => "peterparker@mail.com",
    "age" => 18
);
 
// Loop through superhero array
foreach($superhero as $key => $value){
    echo $key . " : " . $value . "<br>";
}
?>

Functions

// Basic syntax

function functionName(){
    // Code to be executed
}

function myFunc($oneParameter, $anotherParameter){
    // Code to be executed
}
// An example
<?php
// Defining function
function whatIsToday(){
    echo "Today is " . date('l', mktime());
}
// Calling function
whatIsToday();
?>
// Another example
<?php
// Defining function
function getSum($num1, $num2){
  $sum = $num1 + $num2;
  echo "Sum of the two numbers $num1 and $num2 is : $sum";
}
 
// Calling function
getSum(10, 20);
?>

Functions with Optional Parameters and Default Values

<?php
// Defining function
function customFont($font, $size=1.5){
    echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>";
}
 
// Calling function
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
?>

Returning Values from a Function

<?php
// Defining function
function getSum($num1, $num2){
    $total = $num1 + $num2;
    return $total;
}
 
// Printing returned value
echo getSum(5, 10); // Outputs: 15
?>
<?php
// Defining function
function divideNumbers($dividend, $divisor){
    $quotient = $dividend / $divisor;
    $array = array($dividend, $divisor, $quotient);
    return $array;
}
 
// Assign variables as if they were an array
list($dividend, $divisor, $quotient) = divideNumbers(10, 2);
echo $dividend;  // Outputs: 10
echo $divisor;   // Outputs: 2
echo $quotient;  // Outputs: 5
?>
<?php
/* Defining a function that multiply a number
by itself and return the new value */
function selfMultiply(&$number){
    $number *= $number;
    return $number;
}
 
$mynum = 5;
echo $mynum; // Outputs: 5
 
selfMultiply($mynum);
echo $mynum; // Outputs: 25
?>

The global Keyword

<?php
$greet = "Hello World!";
 
// Defining function
function test(){
    global $greet;
    echo $greet;
}
 
test(); // Outpus: Hello World!
echo $greet; // Outpus: Hello World!
 
// Assign a new value to variable
$greet = "Goodbye";
 
test(); // Outputs: Goodbye
echo $greet; // Outputs: Goodbye
?>

GET and POST


The GET Method

In general, a URL with GET data will look like this:

http://www.example.com/action.php?name=john&age=24

The POST Method