Unit 1
PHP Data Types
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
Getting the Data Type
You can get the data type of any object by using the var_dump() function.
Example
The var_dump() function returns the data type and the value:
$x = 5;
var_dump($x); O/P : int(5)
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
var_dump($x);
?>
</body>
</html>
PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
$x = "Hello world!";
$y = 'Hello world!';
var_dump($x);
echo "<br>";
var_dump($y);
O/P:
string(12) "Hello world!"
string(12) "Hello world!"
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
An integer must have at least one digit
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or
binary (base 2) notation
In the following example $x is an integer. The PHP var_dump() function returns the data type and
value:
Example
$x = 5985;
var_dump($x);
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential form.
In the following example $x is a float. The PHP var_dump() function returns the data type and
value:
Example
$x = 10.365;
var_dump($x);
O/P:
float(10.365)
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE. Booleans are often used in conditional
testing.
Example
$x = true;
var_dump($x);
O/P:
bool(true)
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type and
value:
Example
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
O/P:
array(3)
{
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
PHP Object
Classes and objects are the two main aspects of object-oriented programming.
A class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the properties and behaviors from the class,
but each object will have different values for the properties.
Let's assume we have a class named Car that can have properties like model, color, etc. We can
define variables like $model, $color, and so on, to hold the values of these properties.
When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the properties
and behaviors from the class, but each object will have different values for the properties.
PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Tip: If a variable is created without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:
Example
$x = "Hello world!";
$x = null;
var_dump($x);
O/P:
NULL
Change Data Type
If you assign an integer value to a variable, the type will automatically be an integer.
If you assign a string to the same variable, the type will change to a string:
Example
$x = 5;
var_dump($x);
$x = "Hello";
var_dump($x);
O/P:
int(5)
string(5) "Hello"
If you want to change the data type of an existing variable, but not by changing the value, you can
use casting.
Casting allows you to change data type on variables:
Example
$x = 5;
$x = (string) $x;
var_dump($x);
O/P:
string(1) "5"
PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to functions and
resources external to PHP.
A common example of using the resource data type is a database call.
We will not talk about the resource type here, since it is an advanced topic.
PHP Casting
Sometimes you need to change a variable from one data type into another, and sometimes you want a
variable to have a specific data type. This can be done with casting.
Change Data Type
Casting in PHP is done with these statements:
(string) - Converts to data type String
(int) - Converts to data type Integer
(float) - Converts to data type Float
(bool) - Converts to data type Boolean
(array) - Converts to data type Array
(object) - Converts to data type Object
(unset) - Converts to data type NULL
Cast to String
To cast to string, use the (string) statement:
Example
$a = 5; // Integer
$b = 5.34; // Float
$c = "hello"; // String
$d = true; // Boolean
$e = NULL; // NULL
$a = (string) $a;
$b = (string) $b;
$c = (string) $c;
$d = (string) $d;
$e = (string) $e;
//To verify the type of any object in PHP, use the var_dump() function:
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($e);
O/P:
string(1) "5"
string(4) "5.34"
string(5) "hello"
string(1) "1"
string(0) ""
Cast to Integer
To cast to integer, use the (int) statement:
$a = 5; // Integer
$b = 5.34; // Float
$c = "25 kilometers"; // String
$d = "kilometers 25"; // String
$e = "hello"; // String
$f = true; // Boolean
$g = NULL; // NULL
$a = (int) $a;
$b = (int) $b;
$c = (int) $c;
$d = (int) $d;
$e = (int) $e;
$f = (int) $f;
$g = (int) $g;
O/P:
int(5)
int(5)
int(25)
int(0)
int(0)
int(1)
int(0)
Cast to Float
To cast to float, use the (float) statement:
$a = 5; // Integer
$b = 5.34; // Float
$c = "25 kilometers"; // String
$d = "kilometers 25"; // String
$e = "hello"; // String
$f = true; // Boolean
$g = NULL; // NULL
$a = (float) $a;
$b = (float) $b;
$c = (float) $c;
$d = (float) $d;
$e = (float) $e;
$f = (float) $f;
$g = (float) $g;
O/P:
float(5)
float(5.34)
float(25)
float(0)
float(0)
float(1)
float(0)
Cast to Boolean
To cast to boolean, use the (bool) statement:
$a = 5; // Integer
$b = 5.34; // Float
$c = 0; // Integer
$d = -1; // Integer
$e = 0.1; // Float
$f = "hello"; // String
$g = ""; // String
$h = true; // Boolean
$i = NULL; // NULL
$a = (bool) $a;
$b = (bool) $b;
$c = (bool) $c;
$d = (bool) $d;
$e = (bool) $e;
$f = (bool) $f;
$g = (bool) $g;
$h = (bool) $h;
$i = (bool) $i;
O/P:
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
If a value is 0, NULL, false, or empty, the (bool) converts it into false, otherwise true.
Even -1 converts to true.
$a = 5; // Integer
$b = 5.34; // Float
$c = "hello"; // String
$d = true; // Boolean
$e = NULL; // NULL
Cast to Array
To cast to array, use the (array) statement:
$a = (array) $a;
$b = (array) $b;
$c = (array) $c;
$d = (array) $d;
$e = (array) $e;
O/P:
array(1) {
[0]=>
int(5)
}
array(1) {
[0]=>
float(5.34)
}
array(1) {
[0]=>
string(5) "hello"
}
array(1) {
[0]=>
bool(true)
}
array(0) {
}
PHP Constants
Constants are like variables, except that once they are defined they cannot be changed or
undefined.
PHP Constants
A constant is an identifier (name) for a simple value. The value cannot be changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
Note: Unlike variables, constants are automatically global across the entire script.
Create a PHP Constant
To create a constant, use the define() function.
Syntax
define(name, value);
Parameters:
name: Specifies the name of the constant
value: Specifies the value of the constant
Example
Create a constant with a case-sensitive name:
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
Welcome to W3Schools.com!
PHP const Keyword
You can also create a constant by using the const keyword.
Example
Create a case-sensitive constant with the const keyword:
const MYCAR = "Volvo";
echo MYCAR;
O/P:
Volvo
const vs. define()
const cannot be created inside another block scope, like inside a function or inside
an if statement.
define can be created inside another block scope.
Constants are Global
Constants are automatically global and can be used across the entire script.
Example
This example uses a constant inside a function, even if it is defined outside the function:
define("GREETING", "Welcome to W3Schools.com!");
function myTest()
echo GREETING;
myTest();
O/P:
Welcome to W3Schools.com!
PHP Magic Constants
PHP Predefined Constants
PHP has nine predefined constants that change value depending on where they are used, also called
the "magic constants".
These magic constants are written with a double underscore at the start and the end, except for the
ClassName::class constant.
Magic Constants
Here are the magic constants, with descriptions and examples:
Constant Description
__CLASS__ If used inside a class, the <?php
class name is returned.
class Fruits {
public function myValue(){
return __CLASS__;
}
$kiwi = new Fruits();
echo $kiwi->myValue();
?>
O/P Fruit
<?php
__DIR__ The directory of the file. echo __DIR__;
?>
C:\awesomesites\w3schools\php
<?php
__FILE__ The file name including the echo __FILE__;
full path. ?>
C:\awesomesites\w3schools\php\
magic_const_file.php
__FUNCTION__ If inside a function, the <?php
function name is returned.
function myValue(){
return __FUNCTION__;
echo myValue();
?>
O/P: myValue
__LINE__ The current line number. <!DOCTYPE html>
<html>
<body>
<?php
echo __LINE__;
?>
</body>
</html>
O/P:
__METHOD__ If used inside a function <?php
that belongs to a class, both
class and function name is class Fruits {
returned.
public function myValue(){
return __METHOD__;
$kiwi = new Fruits();
echo $kiwi->myValue();
?>
O/P;
Fruits::myValue
__NAMESPACE__ If used inside a namespace, <?php
the name of the namespace
is returned. namespace myArea;
function myValue(){
return __NAMESPACE__;
?>
<?php
echo myValue();
?>
myArea
__TRAIT__ If used inside a trait, the <?php
trait name is returned. trait message1 {
public function msg1() {
echo __TRAIT__;
}
}
class Welcome {
use message1;
}
$obj = new Welcome();
$obj->msg1();
?>
message1
<?php
ClassName::class Returns the name of the namespace myArea;
specified class and the class Fruits {
name of the namespace, if public function myValue(){
any. return Fruits::class;
}
}
?>
<?php
$kiwi = new Fruits();
echo $kiwi->myValue();
?>
myArea\Fruits
Note:
The magic constants are case-insensitive, meaning __LINE__ returns the same as __line__.
PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th
power
PHP Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of
the assignment expression on the right.
Assignment Same as... Description
x=y x=y The left operand gets set to the value of the
expression on the right
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
ADVERTISEMENT
PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result
== Equal $x == $y Returns true if
$x is equal to
$y
=== Identical $x === $y Returns true if
$x is equal to
$y, and they
are of the same
type
!= Not equal $x != $y Returns true if
$x is not equal
to $y
<> Not equal $x <> $y Returns true if
$x is not equal
to $y
!== Not identical $x !== $y Returns true if
$x is not equal
to $y, or they
are not of the
same type
> Greater than $x > $y Returns true if
$x is greater
than $y
< Less than $x < $y Returns true if
$x is less than
$y
>= Greater than or equal to $x >= $y Returns true if
$x is greater
than or equal
to $y
<= Less than or equal to $x <= $y Returns true if
$x is less than
or equal to $y
<=> Spaceship $x <=> $y Returns an
integer less
than, equal to,
or greater than
zero,
depending on
if $x is less
than, equal to,
or greater than
$y. Introduced
in PHP 7.
PHP Increment / Decrement Operators
The PHP increment operators are used to increment a variable's value.
The PHP decrement operators are used to decrement a variable's value.
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
PHP Logical Operators
The PHP logical operators are used to combine conditional statements.
Operator Name Example Result
and And $x and $y True if both $x and $y are
true
or Or $x or $y True if either $x or $y is
true
xor Xor $x xor $y True if either $x or $y is
true, but not both
&& And $x && $y True if both $x and $y are
true
|| Or $x || $y True if either $x or $y is
true
! Not !$x True if $x is not true
PHP String Operators
PHP has two operators that are specially designed for strings.
Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of
$txt1 and $txt2
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to
$txt1
PHP Array Operators
The PHP array operators are used to compare arrays.
+ Union $x + $y Union of $x and $y
== Equality $x == Returns true if $x and $y have the same key/value pairs
$y
=== Identity $x === Returns true if $x and $y have the same key/value pairs in the
$y same order and of the same types
!= Inequality $x != Returns true if $x is not equal to $y
$y
<> Inequality $x <> Returns true if $x is not equal to $y
$y
!== Non- $x !== Returns true if $x is not identical to $y
identity $y
PHP Conditional Assignment Operators
The PHP conditional assignment operators are used to set a value depending on conditions:
Operator Name Example Result
?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.
The value of $x
is expr2 if expr1 = TRUE.
The value of $x
is expr3 if expr1 = FALSE
?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.
The value of $x
is expr1 if expr1 exists,
and is not NULL.
If expr1 does not exist, or
is NULL, the value of $x
is expr2.
Introduced in PHP 7
PHP if Statements
Conditional statements are used to perform different actions based on different
conditions.
PHP Conditional Statements
Very often when you write code, you want to perform different actions for
different conditions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
if statement - executes some code if one condition is true
if...else statement - executes some code if a condition is true and
another code if that condition is false
if...elseif...else statement - executes different codes for more than
two conditions
switch statement - selects one of many blocks of code to be executed
ExampleGet your own PHP Server
Output "Have a good day!" if 5 is larger than 3:
if (5 > 3) {
echo "Have a good day!";
Example
Check if $a is greater than $b, AND if $a is less than $c:
$a = 200;
$b = 33;
$c = 500;
if ($a > $b && $a < $c ) {
echo "Both conditions are true";
PHP - The if...else Statement
The if...else statement executes some code if a condition is true and another
code if that condition is false.
Example
Output "Have a good day!" if the current time is less than 20, and "Have a good
night!" otherwise:
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
Example
Output "Have a good morning!" if the current time is less than 10, and "Have a
good day!" if the current time is less than 20. Otherwise it will output "Have a
good night!":
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
Short Hand If
To write shorter code, you can write if statements on one line.
Example
One-line if statement:
$a = 5;
if ($a < 10) $b = "Hello";
echo $b
Short Hand If...Else
if...else statements can also be written in one line, but the syntax is a bit
different.
Example
One-line if...else statement:
$a = 13;
$b = $a < 10 ? "Hello" : "Good Bye";
echo $b;
This technique is known as Ternary Operators, or Conditional Expressions.
Nested If
You can have if statements inside if statements, this is
called nested if statements.
Example
An if inside an if:
$a = 13;
if ($a > 10) {
echo "Above 10";
if ($a > 20) {
echo " and also above 20";
} else {
echo " but not above 20";
PHP switch Statement
The switch statement is used to perform different actions based on different
conditions.
The PHP switch Statement
Use the switch statement to select one of many blocks of code to be
executed.
Syntax
switch (expression) {
case label1:
//code block
break;
case label2:
//code block;
break;
case label3:
//code block
break;
default:
//code block
Common Code Blocks
If you want multiple cases to use the same code block, you can specify the
cases like this:
Example
More than one case for each code block:
$d = 3;
switch ($d) {
case 1:
case 2:
case 3:
case 4:
case 5:
echo "The weeks feels so long!";
break;
case 6:
case 0:
echo "Weekends are the best!";
break;
default:
echo "Something went wrong";
PHP Loops
In the following chapters you will learn how to repeat code by using loops in
PHP.
PHP Loops
Often when you write code, you want the same block of code to run over and
over again a certain number of times. So, instead of adding several almost equal
code-lines in a script, we can use loops.
Loops are used to execute the same block of code again and again, as long as a
certain condition is true.
In PHP, we have the following loop types:
while - loops through a block of code as long as the specified condition is
true
do...while - loops through a block of code once, and then repeats the
loop as long as the specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
The following chapters will explain and give examples of each loop type.
The PHP while Loop
The while loop executes a block of code as long as the specified condition is
true.
Example
Print $i as long as $i is less than 6:
$i = 1;
while ($i < 6) {
echo $i;
$i++;
Alternative Syntax
The while loop syntax can also be written with the endwhile statement like
this
Example
Print $i as long as $i is less than 6:
$i = 1;
while ($i < 6):
echo $i;
$i++;
endwhile;
The PHP do...while Loop
The do...while loop will always execute the block of code at least once, it will
then check the condition, and repeat the loop while the specified condition is
true.
Example
Print $i as long as $i is less than 6:
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);
The PHP for Loop
The for loop is used when you know how many times the script should run.
Example
Print the numbers from 0 to 10:
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
PHP foreach Loop
The foreach loop - Loops through a block of code for each element in an
array or each property in an object.
The foreach Loop on Arrays
The most common use of the foreach loop, is to loop through the items of an
array.
Example
Loop through the items of an indexed array:
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
echo "$x <br>";