Introduction to PHP
1331204 PABI
Science Calculations
System
System
C uses curly
braces { }
for code
blocks.
Scripting/
Interpreted
http://en.wikipedia.org/wiki/
History_of_programming_languages
PHP
• PHP is an acronym for "PHP: Hypertext
Preprocessor”
• PHP is a widely-used, open source scripting
language (Interpreted Language)
• PHP scripts are executed on the server
• PHP is free to download and use
<h1>Hello from Dr. Chuck's HTML Page</h1>
<p>
<?php
echo "Hi there.\n";
$answer = 6 * 7;
echo "The answer is $answer, what ";
echo "was the question again?\n";
?>
</p>
<p>Yes another paragraph.</p>
PHP from the Command Line
• You can run PHP from the
command line - the output <?php
simply comes out on the echo("Hello World!");
terminal. echo("\n");
• It does not have to be part
?>
of a request-response cycle.
Basic PHP
• Interpreted
• File Extension: ‘.php’ (not a requirement)
• File content starts with <?php
• Ends with ?> (Note: Note needed if the file contains
pure PHP Script)
• Executed by backend server application or with
“php” command/Interpreter e.g: #php file.php
Basic Syntax
Keywords
abstract and array() as break case catch
class clone const continue declare default
do else elseif end declare endfor
endforeach endif endswitch endwhile
extends final for foreach function global
goto if implements interface instanceof
namespace new or private protected public
static switch $this throw try use var while
xor
http://php.net/manual/en/
reserved.php
Variable Names
• Start with a dollar sign ($) followed by a letter or underscore,
followed by any number of letters, numbers, or underscores
• Case matters
$abc = 12; abc = 12;
$total = 0; $2php = 0;
$largest_so_far = 0; $bad-punc = 0;
http://php.net/manual/en/
language.variables.basics.php
Strings
• String literals can use single quotes or double quotes.
• The backslash (\) is used as an “escape” character.
• Strings can span multiple lines - the newline is part of the
string.
• In double-quoted strings, variable values are expanded.
• Concatenation is the "." not "+" (more later).
http://php.net/manual/en/
language.types.string.php
<?php
Double
echo "this is a simple string\n"; Quote
echo "You can also have embedded newlines in
strings this way as it is
okay to do";
// Outputs: This will expand:
// a newline
echo "This will expand: \na newline";
// Outputs: Variables do 12
$expand = 12;
echo "Variables do $expand\n";
<?php Single
echo 'this is a simple string'; Quote
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
Comments in PHP
echo 'This is a test'; // This is a c++ style comment
/* This is a multi line comment
yet another line of comment */
echo 'This is yet another test';
echo 'One Final Test'; # This is a shell-style comment
http://php.net/manual/en/language.basic-
syntax.comments.php
Output
• echo is a language construct - <?php
$x = "15" + 27;
can be treated like a function
echo $x;
with one parameter. Without
echo("\n");
parentheses, it accepts multiple echo $x, "\n";
parameters. print $x;
• print is a function - only one print "\n";
print($x);
parameter, but parentheses are
optional so it can look like a print("\n");
language construct. ?>
Expressions
Expressions
• Completely normal like other languages ( + - / * )
• More agressive implicit type conversion
<?php
$x = "15" + 27;
echo($x); 42
echo("\n");
?>
Expressions
• Expressions evaluate to a value. The value can be a string,
number, boolean, etc.
• Expressions often use operations and function calls. There is
an order of evaluation when there is more than one operator
in an expression.
• Expressions can also produce objects like arrays.
Operators of Note
• Increment / Decrement ( ++ -- )
• String concatenation ( . )
• Equality ( == != )
• Identity/Identical ( === !== ) (Same information and same
datatype)
• Ternary ( ? : )
• Null Coalescing Operator (??) (PHP 7+)
• Side-effect Assignment ( += -= .= etc.)
• Ignore the rarely-used bitwise operators ( >> << ^ | & )
Increment / Decrement
• These operators allow you to both retrieve and increment /
decrement a variable.
• They are generally avoided in civilized code.
$x = 12;
$y = 15 + $x++; x is 13 and y is 27
echo "x is $x and y is $y \n";
$x = 12;
$y = 15 + ++$x; x is 13 and y is 28
echo "x is $x and y is $y \n";
Increment / Decrement
• These operators allow you to both retrieve and increment /
decrement a variable.
• They are generally avoided in civilized code.
$x = 12;
$y = 15 + $x; x is 13 and y is 27
$x = $x + 1;
echo "x is $x and y is $y \n";
$x = 12;
$y = 15 + ($x + 1); x is 13 and y is 28
echo "x is $x and y is $y \n";
String Concatenation
PHP uses the period character for concatenation, because the
plus character would instruct PHP to do the best it could to add
the two things together, converting if necessary.
$a = 'Hello ' . 'World!'; Hello World!
echo $a . "\n";
Ternary
The ternary operator comes from C. It allows conditional
expressions. It is like a one-line if-then-else. Like all “contraction”
syntaxes, we must use it carefully.
$www = 123;
$msg = $www > 100 ? "Large" : "Small" ;
echo "First: $msg \n";
$msg = ( $www % 2 == 0 ) ? "Even" : "Odd";
echo "Second: $msg \n"; First: Large
$msg = ( $www % 2 ) ? "Odd" : "Even";
Second: Odd
echo "Third: $msg \n";
Third: Odd
Side-Effect Assignment
These are pure contractions. Use them sparingly.
echo "\n";
$out = "Hello";
$out = $out . " ";
$out .= "World!";
$out .= "\n"; Hello World!
echo $out; Count: 1
$count = 0;
$count += 1;
echo "Count: $count\n";
Null Coalescing Operator
This operator returns its first operand if it is set and not NULL .
Otherwise it will return its second operand.
$x = null;
$x = $x ?? 3; x = 3
$x = 4;
$x = $x ?? 3; x = 4
Null Coalescing Assignment Operator (PHP 7.4+)
$x = null;
$x ??= 3; x = 3
Conversion / Casting
As PHP evaluates expressions, sometimes values in the expression
need to be converted from one type to another as the computations
are done.
• PHP does aggressive implicit type conversion (casting).
• You can also make type conversion (casting) explicit with
casting operators.
In PHP, division forces
Casting operands to be floating
point. PHP converts
$a = 56; $b = 12; expression values
$c = $a / $b; silently and
echo "C: $c\n"; agressively.
$d = "100" + 36.25 + TRUE;
echo "D: ". $d . "\n";
echo "D2: ". (string) $d . "\n"; C: 4.66666666667
$e = (int) 9.9 - 1; D: 137.25
echo "E: $e\n"; D2: 137.25
$f = "sam" + 25; E: 8
echo "F: $f\n";
F: 25
$g = "sam" . 25;
echo "G: $g\n";
G: sam25
PHP vs. Python
$x = "100" + 25; x = int("100") + 25
echo "X: $x\n"; print "X:", x
$y = "100" . 25; y = "100" + str(25)
echo "Y: $y\n"; print "Y:", y
$z = "sam" + 25; z = int("sam") + 25
echo "Z: $z\n"; print "Z:", z
X: 125 X: 125
Y: 10025 Y: 10025
Z: 25 Traceback:"cast.py", line 5
z = int("sam") + 25;
ValueError: invalid literal
Casting
The concatenation operator
tries to convert its operands to
strings.
echo "A".FALSE."B\n"; TRUE becomes an integer 1
echo "X".TRUE."Y\n"; and then becomes a string.
FALSE is “not there” - it is
even “smaller” than zero, at
AB least when it comes to width.
X1Y
Equality versus Identity
The equality operator (==) in PHP is far more agressive than in
most other languages when it comes to data conversion during
expression evaluation.
if ( 123 == "123" ) print ("Equality 1\n");
if ( 123 == "100"+23 ) print ("Equality 2\n");
if ( FALSE == "0" ) print ("Equality 3\n");
if ( (5 < 6) == "2"-"1" ) print ("Equality 4\n");
if ( (5 < 6) === TRUE ) print ("Equality 5\n");
Control Structures
Conditional - if
• Logical operators ( == != < > <= >= && || ! )
• Curly braces
<?php
$ans = 42;
if ( $ans == 42 ) {
print "Hello world!\n";
} else {
print "Wrong answer\n"; Hello World!
}
?>
Whitespace Does Not Matter
<?php
$ans = 42;
if ( $ans == 42 ) {
print "Hello world!\n";
} else {
print "Wrong answer\n";
}
?>
<?php $ans = 42; if ( $ans == 42 ) { print
"Hello world!\n"; } else { print "Wrong answer\n"; }
?>
Which Style do You Prefer?
<?php
$ans = 42;
<?php if ( $ans == 42 )
$ans = 42; {
if ( $ans == 42 ) { print "Hello world!\n";
print "Hello world!\n"; }
} else { else
print "Wrong answer\n"; {
} print "Wrong answer\n";
?> }
?>
Aesthetics?
Suggestion: Follow PHP Standard Recommendation (PSR) https://www.php-fig.org/psr/
PSR-12 for coding standard https://www.php-fig.org/psr/psr-12/
Multi-way x<2
ye
s
print 'Small'
$x = 7; no
ye
if ( $x < 2 ) { s
x<10 print 'Medium'
print "Small\n";
} elseif ( $x < 10 ) { no
print "Medium\n";
} else { print 'LARGE'
print "LARGE\n";
}
print "All done\n";
print 'All Done'
Curly Braces are Not
Required
if ($page == "Home") echo "You selected Home";
elseif ($page == "About") echo "You selected About";
elseif ($page == "News") echo "You selected News";
elseif ($page == "Login") echo "You selected Login";
elseif ($page == "Links") echo "You selected Links";
if ($page == "Home") { echo "You selected Home"; }
elseif ($page == "About") { echo "You selected About"; }
elseif ($page == "News") { echo "You selected News"; }
elseif ($page == "Login") { echo "You selected Login"; }
elseif ($page == "Links") { echo "You selected Links"; }
While Loop
$fuel = 10;
while ($fuel > 1) {
print "Vroom vroom\n";
}
A while loop is a “zero-
trip” loop with the test
at the top before the $fuel = 10;
first iteration starts. We while ($fuel > 1) {
hand construct the print "Vroom vroom\n";
$fuel = $fuel - 1;
iteration variable to
}
implement a counted
loop.
Do-while Loop
$count = 1;
do {
echo "$count times 5 is " . $count * 5;
echo "\n";
} while (++$count <= 5);
A do-while loop is a “one- 1 times 5 is 5
trip” loop with the test at 2 times 5 is 10
the bottom after the first 3 times 5 is 15
iteration completes. 4 times 5 is 20
5 times 5 is 25
For Loop
for($count=1; $count<=6; $count++ ) {
echo "$count times 6 is " . $count * 6;
echo "\n";
} 1 times 6 is 6
2 times 6 is 12
A for loop is the 3 times 6 is 18
simplest way to 4 times 6 is 24
construct a counted 5 times 6 is 30
loop. 6 times 6 is 36
Loop runs while TRUE
Before loop (top-test) Run after each
starts iteration.
for($count=1; $count<=6; $count++ ) {
echo "$count times 6 is " . $count * 6;
echo "\n";
} 1 times 6 is 6
2 times 6 is 12
A for loop is the 3 times 6 is 18
simplest way to 4 times 6 is 24
construct a counted 5 times 6 is 30
loop. 6 times 6 is 36
Breaking Out of a Loop
• The break statement ends the current loop and jumps to the
statement immediately following the loop.
• It is like a loop test that can happen anywhere in the body of the loop.
for($count=1; $count<=600; $count++ ) { Count: 1
if ( $count == 5 ) break; Count: 2
echo "Count: $count\n"; Count: 3
} Count: 4
echo "Done\n"; Done
Finishing an Iteration with
continue
•The continue statement ends the current iteration. jumps to the top of
the loop, and starts the next iteration.
Count: 1
for($count=1; $count<=10; $count++ ) { Count: 3
if ( ($count % 2) == 0 ) continue; Count: 5
echo "Count: $count\n"; Count: 7
} Count: 9
echo "Done\n"; Done
Function
• The real power of PHP comes from its functions.
• PHP has more than 1000 built-in functions, and in
addition you can create your own custom
functions.
User Defined Function
Besides the built-in PHP functions, it is possible to
create your own functions.
• A function is a block of statements that can be used repeatedly in a
program.
• A function will not execute automatically when a page loads or script
executed.
• A function will be executed by a call to the function.
Summary
PHP is just another tools for programming
– don’t learn the language, learn
programming.