Intro-to-PHP
Intro-to-PHP
to PHP
PRESENTED BY: ENGR. ROGER R. ABULENCIA
1
What is PHP?
PHP == ‘PHP Hypertext Preprocessor’
Open-source, server-side scripting language
Used to generate dynamic web-pages
PHP scripts reside between reserved PHP tags
◦ This allows the programmer to embed PHP scripts within HTML pages
2
What is PHP (cont’d)
Interpreted language, scripts are parsed at run-time rather than compiled
beforehand
Executed on the server-side
Source-code not visible by client
‘View Source’ in browsers does not display the PHP code
Various built-in functions allow for fast development
Compatible with many popular databases
3
3(+1) Tier architecture
voice
HTML
SMS Remote
services Web Service
SMS system
Client
application
Header
Footer
5
What does PHP code look like?
Structurally similar to C/C++
Supports procedural and object-oriented paradigm (to some degree)
All PHP statements end with a semi-colon
Each PHP script must be enclosed in the reserved PHP tag
<?php
…
?>
6
Comments in PHP
Standard C, C++, and shell comment symbols
# Shell-style comments
/* C-style comments
These can span multiple lines */
Example:
PHP code
<?php
// Single-line comment
# Another single-line comment
/*
Multi-line comment
*/
echo "This is a PHP script!";
?>
7
Variables in PHP
PHP variables must begin with a “$” sign
Case-sensitive ($Foo $foo $fOo)
Global and locally-scoped variables
Global variables can be used anywhere
Local variables restricted to a function or class
Certain variable names reserved by PHP
Form variables ($_POST, $_GET)
Server variables ($_SERVER)
Etc.
• Variables in PHP:
• Must start with a $ sign.
• Are case-sensitive ($Foo ≠ $foo).
• Can be global (accessible anywhere) or local (restricted to a function or class).
• Special variable types include:
• $_POST and $_GET for handling form inputs.
• $_SERVER for accessing server environment data.
8
Variable usage
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
• PHP supports various data types, and variable manipulation depends on context:
• Numerical operations are valid on numbers.
• Invalid operations on incompatible types trigger errors.
9
Echo
The PHP command ‘echo’ is used to output
the parameters passed to it
The typical usage for this is to send data to the
client’s web-browser
Syntax
echo string arg1 [, string argn...]
10
Echo example
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
11
Arithmetic Operations
<?php
$a=15;
$b=30;
$total=$a+$b;
Print $total;
Print “<p><h1>$total</h1>”;
// total is 45
?>
$a - $b // subtraction
$a * $b // multiplication
$a / $b // division
$a += 5 // $a = $a+5
12
Concatenation
Use a period to join strings into one.
<?php
$string1=“Hello”;
$string2=“PHP”;
$string3=$string1 . “ ” . $string2;
Print $string3;
?>
Hello PHP
13
Escaping the Character
If the string has a set of double quotation marks that must remain
visible, use the \ [backslash] before the quotation marks to ignore and
display them.
<?php
$heading=“\”Computer Science\””;
Print $heading;
?>
“Computer Science”
• Use a backslash (\) to escape special characters in strings, such as double quotes (").
• This ensures characters like quotes are displayed as part of the string.
14
PHP Control Structures
if (expr) statement
<?php
if ($a > $b) {
echo "a is bigger than b";
$b = $a;
}
?>
<?php
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>
15
PHP Control Structures
if ($foo == 0) {
echo ‘The variable foo is equal to 0’;
}
else if (($foo > 0) && ($foo <= 5)) {
echo ‘The variable foo is between 1 and 5’;
}
else {
echo ‘The variable foo is equal to ‘.$foo;
}
• This shows how PHP handles conditional branching using if, else if, and else
statements. In PHP, these control structures allow you to execute different blocks of
code based on whether certain conditions are true or false.
• How It Works?
• When the script runs, it starts at the top condition (if ($foo == 0)) and checks
it. If $foo is zero, the code inside that block executes, and no other conditions
are checked.
• If $foo is not zero, it moves to the elseif block. If $foo is between 1 and 5, that
block executes.
• If neither of the previous conditions is true, then the else block runs,
providing a fallback message for any other value of $foo.
16
PHP Control Structures
<?php
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
break;
default:
echo ‘Enter correct option’;
}
?>
17
Loops
while (condition) {statements;}
<?php
$count=0;
While($count<3)
{
Print “hello PHP. ”;
$count += 1;
// $count = $count + 1;
// or
// $count++;
?>
18
Loops
for (expr1; expr2; expr3)
statement
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>
• A for loop is often used when the number of iterations is known beforehand.
• Syntax: for (initialization; condition; increment/decrement).
19
Loops
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
echo “$value \n”;
}
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value);//break the reference
?>
20
Loops
foreach ($arr as $key => $value) {
echo "Key:$key; Value:$value<br />\n";
}
• The foreach loop iterates over elements in an array, associating a key with its
corresponding value.
• A do-while loop ensures the block of code runs at least once before the condition is
checked.
21
Arrays
An array in PHP is actually an ordered map which maps
values to keys.
An array can be thought of in many ways:
• Arrays are ordered maps in PHP that associate values with keys. They can function as:
• Linear arrays (e.g., indexed arrays)
• Hash tables (key-value pairs)
• Stacks/Queues (Last In First Out, First In First Out)
• Multidimensional arrays
22
Arrays
Kinds of arrays:
◦ numeric arrays.
◦ associative arrays.
◦ multi dimensional arrays.
23
Arrays
In numeric arrays each key value corresponds to numeric values.
They can be divided into two categories
1.automatic numeric array index.
2.manual array numeric index.
automatic numeric array index
<?php
$x=array(1,2,3);
print_r($x);
?>
o/p: array(0=>1,1=>2,2=>3)
24
Arrays
Manual array numeric index
<?php
$x[2]=10; $x[3]=50;//$x=array(2=>10,3=>50);
echo $x[2]; echo $x[3];
?>
Associative arrays
In associated arrays each ID associated with its value
<?php
$x=array(“ab”=>1,”cd”=>2,”xy”=>3);
print_r($x);
?>
25
Arrays
Multidimensional Arrays-An array contains one or more arrays
<?php
$z=array(array(10,20,30),array(40,50,60));
print_r($z);
?>
Array ( [0] => Array ( [0] => 10 [1] => 20 [2] => 30 )
[1] => Array ( [0] => 40 [1] => 50 [2] => 60 ) )
26
Arrays
<?php
$x=array(“ab”=>1,array(2,3,4),”cd”=>8);
print_r($x);
?>
Array ( [“ab”] => 1 [0] => Array ( [0] => 2 [1] => 3 [2] => 4
) [”cd”] => 8 )
27
Arrays
<?php
$x=array(3=>4,array(2,3,4),5);
print_r($x);
?>
Array ( [3] => 4 [4] => Array ( [0] => 2 [1] => 3 [2] =>
4 ) [5] => 5 )
28
Arrays
Array operations
sort
ksort
rsort
krsort
array_merge
array_combine
array_intersect
29
Date Display
$datedisplay=date(“yyyy/m/d”);
print $datedisplay;
2024/12/7
$datedisplay=date(“l, F J, Y”);
print $datedisplay;
• Format Specifiers:
• Y: Full year (e.g., 2024).
• m: Month with leading zeros (e.g., 12 for December).
• d: Day of the month with leading zeros (e.g., 07).
• Double Quotes:
• Ensure you're using standard double quotes (") instead of typographic quotes
(“”) in the date() function.
30
Month, Day & Date Format Symbols
M Jan
F January
m 01
n 1
Day of Month d 01
Day of Month J 1
Day of Week l Monday
Day of Week D Mon
It describes how PHP handles date and time formatting using predefined format
symbols. These symbols allow developers to customize the output of date and time in a
readable format.
31
Functions
Overview: Functions are blocks of code designed to perform specific tasks. They must
be defined before being called. Unlike variables, function names are not case-sensitive.
• Key Points:
• Functions must be defined before they can be called.
• Function names are not case-sensitive.
• Arguments allow dynamic behavior within the function.
32
Functions example
<?php
// This is a function
function foo($arg_1, $arg_2)
{
$arg_2 = $arg_1 * $arg_2;
return $arg_2;
}
• Function Definition: foo is a reusable function that accepts arguments and performs
operations.
• Parameters and Arguments: $arg_1 and $arg_2 demonstrate how data is passed into
the function.
• Return Value: return allows the function to send back a value to the caller.
• Reuse of Code: The function is called twice with the same arguments, showcasing
how functions avoid redundancy.
33
Include Files
include “header.php”;
include (“footer.php”);
This inserts files; the code in files will be inserted into current code.
require is identical to include except upon failure it will also
produce a fatal E_COMPILE_ERROR level error. In other words, it
will halt the script whereas include only emits a warning
(E_WARNING) which allows the script to continue.
• The include statement imports external files into the script. If the file is missing, it
emits a warning but continues execution.
• require works similarly but stops execution with a fatal error if the file is missing.
34
Include Files
The include_once statement includes and evaluates the
specified file during the execution of the script.
This is a behavior similar to the include statement, with the only
difference being that if the code from a file has already been
included, it will not be included again.
The require_once statement is identical to require except
PHP will check if the file has already been included, and if so, not
include (require) it again
• include_once and require_once ensure files are included only once during execution.
35
Thank you!
36