PHP INTRODUCTION
PHP
Stands for PHP: Hypertext Preprocessor
Server-side scripting language
Websites built in PHP
Facebook.com
Yahoo.com
PHP vs HTML
PHP executed on server
HTML directly rendered on browser
Basic Syntax
<?php
echo "<h1>My Heading Level One</h1>";
print("<h2>My Heading Level Two</h2>");
echo "<h3>My Heading Level Three</h3>";
?>
Comments in PHP
Makes code more readable and understandable
Help other developers to describe the code and what it is
trying to do
Used in documenting a set of code or part of a program
Single Line Comment
>>Two (2) Types of comment
- Single Line Comment
- Multi-line or Multiple line Comment
Comments in PHP Cont’d.
Single Line Comment
<?php
// This is a single line comment
// These cannot be extended to more lines
echo "hello world!!!";
# This is also a single line comment
?>
Comments in PHP Cont’d.
Multi-line or Multiple line Comment:
<?php
/* This is a multi line comment
In PHP variables are written
by adding a $ sign at the beginning.*/
$geek = "hello world!";
echo $geek;
?>
PHP in HTML and HTML in PHP
PHP is an HTML-embedded server-side scripting language.
Anything in a PHP script that is not contained within <?php
?> tags is ignored by the PHP compiler and passed directly
to the web browser.
EXAMPLE:
<head></head>
<body class="page_bg">
Hello, today is <?php echo date('l, F jS, Y'); ?>.
</body>
</html>
PHP in HTML and HTML in PHP
EXAMPLE:
<head></head>
<body class="page_bg">
Hello, today is <?php
echo date('l, F jS, Y') . “© <small>Bok</small>”;
echo
?>.
</body>
</html>
Case Sensitivity in PHP
Sensitive of whitespace $sum = $var1
Tabs, spaces, and carriage return +
Treats multiple lines as a single $var2;
command
Example:
// "\n" for new line
echo $sum, "\n";
<?php
// PHP code illustrate the whitespace
insensitivity $sum1 = $var1 + $var2;
$var1 = 15; echo $sum1;
$var2 = ?>
30;
Case Sensitivity in PHP Cont’d.
PHP is case-sensitive echo $variable;
Keywords, functions and class names ECHO $variable;
are NOT case-sensitive
EcHo $variable;
Except variables
<?php
// but this line will show RUNTIME
// Here we can see that all echo ERROR as
// statements are executed in the same // "Undefined Variable"
manner
echo $VARIABLE
?>
$variable = 25;
Blocks in PHP
<?php
$var = 50;
if ($var>0){
echo ("Positive as \n");
echo ("greater than 0");
}
?>
References
https://www.geeksforgeeks.org
PHP Data Types
Specifies the amount of memory that allocates to the variable associated with
it.
PHP basic data types
Scalar
Compound
special
Scalar data types
A variable is a scalar when it holds a single value
4 types of scalar data types
Integer
Float
String
bool
Integer Scalar data types
Whole number
Within the set {…-3,-2,-2,0,1,2,3…}
$population = 20000000;
$temperature = -14 ;
Float Scalar data types
Floating point numbers, also known as floats, doubles or real numbers.
Numbers that have fractional component.
Can contain positive and negative values.
Exampe:
$length = 145.78;
$growthRate = -5.216;
Boolean Scalar data types
Simplest data type
Used for values that are either true or false
Case-insensitive
Means { true is equal to TRUE}
String Scalar data types
A sequence of characters
Can be text, content of an image file etc.
Example:
$today = 'Today is a nice day';
Compound data types
A data type that can contain more category
than one value at a time Objects are defined as instances of
Example: user defined classes that can hold
both values and functions
<?php
$intArray = array( 10, 20 , 30);
echo "First Element: $intArray[0]\n";
echo "Second Element: $intArray[1]\n";
echo "Third Element: $intArray[2]\n";
?>
Arrays and Object fall into this
Special data types
Resource
Used for variables that hold data or reference of an external resource
Null
Does not contain any value
PHP variables
Stores a value of any type e.g., a string, a number, an array, an object, or a
resource.
Value holder
Syntax:
$variableName = value;
Naming rules of variables
Must start with the dollar sign ($).
First character after the dollar sign ($) must be a letter (a-z) or an underscore (_)
Remaining characters can be underscores, letters or numbers
Variable names are case-sensitive
Variable data types
PHP is a loosely typed programming language, means that when you define a
variable, you don’t specify its data type.
Type casting
PHP handles the type conversion automatically based on the context in which
you use the variables.
Example:
<?php
$x = 20;
$y = '10'; // a string
$z = $x + $y; // $y is converted to an integer
echo $z; // 30
Type casting Cont’d.
Example:
<?php
$x = 20;
$y = '10'; // a string
$z = $x + (int)$y; // $y cast to an integer
echo $z; // 30
Finding data types of variables
PHP provides a built-in function gettype() that returns the data type of a variable
Example:
<?php
$int = 10; // integer
$str = 'this is a string'; // string
$bool = true; // boolean
$d = 3.14; // float
echo gettype($int), '<br>';
echo gettype($str) , '<br>';
echo gettype($bool), '<br>';
echo gettype($d), '<br>';
Changing data type of variables
use settype() function
Example:
<?php
$f = 20.05;
echo $f . '<br>'; // float number
settype($f, 'integer');
echo $f . '<br>'; // 20 integer number
settype($f, 'string');
echo $f . '<br>'; // '20' string
settype($f, 'float');
echo $f . '<br>'; // 20 float number
Testing data types of variables
Function Name Meaning
is_int($var); Return true if $var is an integer, otherwise
return false.
is_string($var); Return true if $var is a string, otherwise
return false.
is_bool($var); Return true if $var is a Boolean, otherwise
return false.
is_float($var); Return true if $var is a float, otherwise
return false.
is_long($var); Return true if $var is a long type,
otherwise return false.
is_numeric($var); Return true if $var is a number,
otherwise return false.
is_double($var); Return true if $var is a double, otherwise
return false.
Set and unset variables
Example: $y = 10; // $x is set
<?php if (isset($y)) {
echo '$y is set. <br/>';
$x; // $x is not set } else {
if (isset($x)) { echo '$y is not set. <br/>';
echo '$x is set. <br/>'; }
} else {
echo '$x is not set. <br/>';
}
unset a variable
Example:
<?php unset($x); // $x is not
available anymore
$x = 10; // $x is not set if (isset($x)) {
if (isset($x)) { echo '$x is set. <br>';
echo '$x is set. <br>'; } else {
} else { echo '$x is not set. <br>';
echo '$x is not set. <br>'; }
}
Checking NULL and empty
Example:
<?php
$x = null;
echo is_null($x) ? '$x is null' : '$x is not null';
echo '<br />';
$x = 20;
echo is_null($x) ? '$x is null' : '$x is not null';
empty() function
Example:
<?php
$x = 0;
echo empty($x) ? '$x is empty' : '$x is not empty';
$s = ‘’’’;
echo empty($s) ? '$s is empty' : '$x is not empty';
Variable Scopes
Scope of a variable is defined as its extent in program
within which it can be accessed
PHP has three variable scopes
Local variables
Global variables
Static variable
Local variables
declared within a function
cannot be accessed outside that function local_var();
Example:
<?php // $num outside function local_var() is a
$num = 60; // completely different Variable than that of
function local_var(){ // inside local_var()
// This $num is local to this function echo "Variable num outside local_var() is
// the variable $num outside this function $num \n";
// is a completely different variable
?>
$num = 50;
echo "local num = $num \n";
}
Global variables
declared outside a function
can be accessed directly outside a function
Example:
<?php
$num = 20;
// function to demonstrate use of global variable
function global_var(){
// we have to use global keyword before
// the variable $num to access within
// the function
global $num;
echo "Variable num inside function : $num \n";
}
global_var();
echo "Variable num outside function : $num \n";
?>
Static variable
Example:
<?php
// function to demonstrate
static variables
function static_var(){
// static variable
static $num = 5;
$sum = 2;
$sum++;
$num++;
echo $num, "\n";
echo $sum, "\n";
}
// first function call
static_var();
// second function call
static_var();
?>
PHP | Superglobals
specially-defined array variables
get information about a request or its context
superglobal variables available in PHP:
$GLOBALS[‘namevar’]
$_SERVER[‘namevar’]
$_REQUEST[‘namevar’]
$_GET[‘namevar’]
$_POST[‘namevar’]
$_SESSION[‘namevar’]
$_COOKIE[‘namevar’]
$_FILES[‘namevar’]
$_ENV[‘namevar’]
$GLOBALS
used to access global variables from anywhere in the PHP
script
Example:
<?php
$x = 300;
$y = 200;
function multiplication(){
$GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];
}
multiplication();
echo $z;
?>
$_SERVER
A variable that stores the information about headers,
paths and script locations.
Example:
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
echo "<br>"
?>
$_REQUEST
It is a superglobal variable which is used to collect
the data after submitting a HTML form. $_REQUEST is
not used mostly, because $_POST and $_GET perform
the same task and are widely used.
$_POST
Used to collect data from the HTML form after
submitting it
Method post transfer data and the data is not visible
in the query string
$_GET
Used to collect data from the HTML form after
submitting it
Method get to transfer data and the data is visible in
the query string
PHP Operators
An operator takes one or more values, which are known as
operands, and performs operation on them such as adding
them together.
Most Common Used operators in PHP
Arithmetic Operators
Logical or Relational Operators
Comparison Operators
Conditional or Ternary Operators
Assignment Operators
Spaceship Operators (Introduced in PHP 7)
Array Operators
Increment/Decrement Operators
String Operators
Arithmetic Operators
Perform simple mathematical operations
Non-numeric values are converted automatically to numeric values
List of arithmetic operators:
Arithmetic Operators Example
<?php echo($x ** $y), "\n";
echo($x / $y), "\n";
// variable 1 echo($x % $y), "\n";
$x = 29; ?>
// variable 2
$y = 4;
// some arithmetic operations on
// these two variables
echo($x + $y), "\n";
echo($x - $y), "\n";
echo($x * $y), "\n";
Comparison Operators
Comparison Operators Example
<?php // articles.
var_dump($a == $c) . "\n";
$a = 80; var_dump($a != $b) . "\n";
$b = 50; var_dump($a <> $b) . "\n";
$c = "80"; var_dump($a === $c) . "\n";
var_dump($a !== $c) . "\n";
// Here var_dump function has var_dump($a < $b) . "\n";
been used to var_dump($a > $b) . "\n";
// display structured information. var_dump($a <= $b) . "\n";
We will learn
// about this function in complete var_dump($a >= $b);
details in further
?>
Logical or Relational Operators
Logical or Relational Operators
Example
<?php echo "xor Success \n";
$x = 50; if ($x == 50 && $y == 30)
$y = 30; echo "&& Success \n";
if ($x == 50 || $y == 20)
if ($x == 50 and $y == 30) echo "|| Success \n";
echo "and Success \n"; if (!$z)
if ($x == 50 or $y == 20) echo "! Success \n";
echo "or Success \n";
if ($x == 50 xor $y == 20) ?>
Conditional or Ternary Operators
Syntax:
$var = (condition)? value1 : value2;
Example:
<?php
$x = -12;
echo ($x > 0) ? 'The number is positive' : 'The number is negative';
?>
Assignment Operators
Assignment Operators Example
Example: $y = 30;
<?php $y *= 20;
// simple assign operator echo $y, "\n";
$y = 75; // Divide then assign(quotient) operator
echo $y, "\n"; $y = 100;
// add then assign operator $y /= 5;
$y = 100; echo $y, "\n";
$y += 200; // Divide then assign(remainder) operator
echo $y, "\n"; $y = 50;
// subtract then assign operator $y %= 5;
$y = 70; echo $y;
$y -= 10;
echo $y, "\n"; ?>
// multiply then assign operator
Array Operators
Array Operators Example
Example:
<?php
$x = array("k" => "Car", "l" => "Bike");
$y = array("a" => "Train", "b" => "Plane");
var_dump($x + $y);
var_dump($x == $y) + "\n";
var_dump($x != $y) + "\n";
var_dump($x <> $y) + "\n";
var_dump($x === $y) + "\n";
var_dump($x !== $y) + "\n";
?>
Increment/Decrement Operators
Increment/Decrement Operators
Example:
<?php $x = 2;
$x = 2; echo $x--, " First prints then decrements
echo ++$x, " First increments then prints \n";
\n"; echo $x;
echo $x, "\n";
$x = 2; ?>
echo $x++, " First prints then increments
\n";
echo $x, "\n";
$x = 2;
echo --$x, " First decrements then prints
\n";
echo $x, "\n";
String Operators Example
Example: echo $x . $y . $z, "\n";
<?php $x .= $y . $z;
echo $x;
$x = "Geeks";
$y = "for"; ?>
$z = "Geeks!!!";
Spaceship Operators (Introduced in PHP 7)
Used to compare values but instead of returning Boolean result, it returns integer
values
If both the operands are equal, it returns 0.
If the right operand is greater, it returns -1
If the left operand is greater, it returns 1
Spaceship Operators (Introduced in
PHP 7)
Example: // We can do the same for
<?php Strings
$x = 50; $x = "Ram";
$y = 50; $y = "Krishna";
$z = 25; echo $x <=> $y;
echo $x <=> $y; echo "\n";
echo "\n"; echo $x <=> $y;
echo $x <=> $z; echo "\n";
echo "\n"; echo $y <=> $x;
echo $z <=> $y; ?>
echo "\n";
Operator Precedence
The precedence of an operator specifies how "tightly" it
binds two expressions together.
In general, operators have a set precedence, or order, in
which they are evaluated.
Example:
An expression 10 + 5 * 2, the answer is 20
Associativity
When operators have equal precedence their associativity
decides how the operators are grouped.
For example:
- is left-associative, so 1 - 2 - 3 is grouped as (1 - 2) - 3 and
evaluates to -4.
= is right-associative, so $a = $b = $c is grouped as $a = ($b = $c).
Operator PRECEDENCE and ASSOCIATIVITY
Associativit Operators
y
Highest Precedence
n/a ()
n/a new
right []
right ! ~ ++ --
(int) (double) (string) (array) (object)
left */%
left +-.
left << >>
n/a < <= > >=
n/a == != === !===
Operator PRECEDENCE and ASSOCIATIVITY Cont’d.
Associativit Operators
y
Highest Precedence
left &
left ^
left |
left &&
left ||
left ? :
left = += -= *= /= .= %= |= ^= ~= <<= >>=
right print
left and
left xor
left or
left ,
Lowest Precedence
PHP | Decision Making
Four (4) conditional statements
if statement
if…else statement
if…elseif…else statement
switch statement
if statement Flow Chart
if…else Statement Flow Chart
if…elseif…else Statement
Flow Chart
switch
Statement
Ternary Operators
Syntax: }
(condition) ? if TRUE execute
this : otherwise execute this; // This whole lot can be
Example: written in a
<?php // single line using ternary
$x = -12; operator
if ($x > 0) { echo ($x > 0) ? 'The number is
positive' :
echo "The number is
positive \n"; 'The number is
negative';
}
?>
else {
echo "The number is
negative \n";
PHP | Loops
four (4) types of looping techniques
for loop
while loop
do-while loop
foreach loop
PHP for loop
PHP while loop
PHP do-while Loop
PHP foreach
$scores = [1,2,3];
foreach ($scores as &$score) {
$score *= 2;
}
print_r($scores); // [2, 4, 6]
PHP foreach – used in associative array
Example:
<?php
$name = [
'firstname' => 'John',
'lastname' => 'Doe',
'middlename' => 'Bray'
];
foreach ($name as $key => $value) {
echo $key . ':' . $value . '<br>';
}
PHP foreach – iterate over public
properties of an object
Example: $this->lastName = $lastName;
class Person $this->middleName = $middleName;
{ }
public $firstName; }
public $lastName;
public $middleName; $john = new Person('John', 'Doe', 'Bray');
public function __construct($firstName, $lastName, foreach ($john as $propName => $propValue) {
$middleName)
echo $propName . ': ' . $propValue . '<br>';
{
}
$this->firstName = $firstName;
PHP | Functions
With and without parameter(s)
Reasons in using functions is its capability of the following: Reusability, Easier
error detection, and Easily maintained
Two(2) major types of functions:
Built-in functions : PHP provides us with huge collection of built-in library
functions. These functions are already coded and stored in form of functions. To
use those we just need to call them as per our requirement like, var_dump,
fopen(), print_r(), gettype() and so on.
User Defined Functions : Apart from the built-in functions, PHP allows us to
create our own customized functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary
by simply calling it.
PHP | Functions Cont’d.
Syntax: {
function function_name(){ echo "This is Geeks for Geeks";
executable code; }
}
Example: // Calling the function
funcGeek();
<?php
?>
function funcGeek()
References
https://www.tutorialspoint.com/php/php_variable_types.htm
http://www.phpknowhow.com/basics/data-types/
https://www.geeksforgeeks.org/php-variables-data-types/
https://tutorialink.com
https://www.guru99.com
https://www.learn-php.org
https://www.homeandlearn.co.uk