Unit 2 PHP
Unit 2 PHP
Definition
A variable in PHP is a container used to store data. It starts with a dollar sign ($),
followed by the variable name.
Syntax
$variablename=value;
o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a
number or special symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated as
different variable.
Example
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
Output:
Example 2
<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
Output:
11
PHP data types are used to hold different types of data or values. PHP supports 8 primitive
data types that can be categorized further in 3 types:
1. boolean
2. integer
3. float
4. string
1. array
2. object
1. resource
2. NULL
PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE
(1) or FALSE (0). It is often used with conditional statements. If the condition is correct, it
returns TRUE otherwise FALSE.
Example:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Output:
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers,
i.e., numbers without fractional part or decimal points.
Example:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold
numbers with a fractional or decimal point, including a negative or positive sign.
Example:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even
special characters.
String values must be enclosed either within single quotes or in double quotes. But both
are treated differently. To clarify this, see the example below:
Example:
<?php
$company = "Javatpoint";
//both single and double quote statements will treat different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>
Output:
Hello Javatpoint
Hello $company
PHP Array
An array is a compound data type. It can store multiple values of same data type in a single
variable.
Example:
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
PHP object
Objects are the instances of user-defined classes that can store both values and functions.
They must be explicitly declared.
Example:
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
Output:
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some
function calls or references to external PHP resources. For example - a database call. It is
an external resource.
This is an advanced topic of PHP, so we will discuss it later in detail with examples.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it
in capital letters as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
Output:
No output
PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the
script except for magic constants, which are not really constants. PHP constants can be
defined by 2 ways:
1. Using define() function
2. Using const keyword
PHP constant: define()
Use the define() function to create a constant. It defines constant
at run time. Let's see the syntax of define() function in PHP.
Example
<?php
define("MESSAGE","Hello JavaTpoint PHP");
echo MESSAGE;
?>
Output:
Hello JavaTpoint PHP
Example
<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
Output:
Hello const by JavaTpoint PHP
Constant() function
There is another way to print the value of constants using constant() function instead of
using the echo statement.
Syntax
The syntax for the following constant function:
constant (name)
<?php
define("MSG", "JavaTpoint");
echo MSG, "</br>";
echo constant("MSG");
//both are similar
?>
Output:
JavaTpoint
JavaTpoint
Magic Constants
Magic constants are the predefined constants in PHP which get changed on the basis of
their use. They start with double underscore (__) and ends with double underscore.
They are similar to other predefined constants but as they change their values with the
context, they are called magic constants.
There are nine magic constants in PHP. In which eight magic constants start and end
with double underscores (__).
1. __LINE__
2. __FILE__
3. __DIR__
4. __FUNCTION__
5. __CLASS__
6. __TRAIT__
7. __METHOD__
8. __NAMESPACE__
9. ClassName::class
Using Operators
Operators are symbols that instruct the PHP processor to carry out specific actions. For
example, the addition (+) symbol instructs PHP to add two variables or values, whereas
the greater-than (>) symbol instructs PHP to compare two values.
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
Arithmetic Operators
The PHP arithmetic operators are used in conjunction with numeric values to perform
common arithmetic operations such as addition, subtraction, multiplication, and so on.
Operator Name Example Output
Example
<?php
$x = 10;
$y = 4;
echo($x + $y) . "<br>";
echo($x - $y) . "<br>";
echo($x * $y) . "<br>";
echo($x / $y) . "<br>";
echo($x % $y) . "<br>";
Output
14
6
40
2.5
2
Assignment Operators
= Assign $x = $y The left operand gets set to the value of the expression
on the right
Example
<?php
$x = 10;
echo $x . "<br>";
$x = 20;
$x += 30;
echo $x . "<br>";
$x = 50;
$x -= 20;
echo $x . "<br>";
$x = 5;
$x *= 25;
echo $x . "<br>";
$x = 50;
$x /= 10;
echo $x . "<br>";
$x = 100;
$x %= 15;
echo $x . "<br>";
Output
10
50
30
125
5
10
Comparison Operators
Comparison operators are used to compare two values in a Boolean fashion.
=== Identical $x === $y True if $x is equal to $y, and they are of the same type
!== Not identical $x !== $y True if $x is not equal to $y, or they are not of the same type
Example
<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true
echo "<br>";
var_dump($x === $z); // Outputs: boolean false
echo "<br>";
var_dump($x != $y); // Outputs: boolean true
echo "<br>";
var_dump($x !== $z); // Outputs: boolean true
echo "<br>";
var_dump($x < $y); // Outputs: boolean true
echo "<br>";
var_dump($x > $y); // Outputs: boolean false
echo "<br>";
var_dump($x <= $y); // Outputs: boolean true
echo "<br>";
var_dump($x >= $y); // Outputs: boolean false
echo "<br>";
Output
bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
Example
<?php
$x = 10;
echo ++$x . "<br>"; // Outputs: 11
echo $x . "<br>"; // Outputs: 11
$x = 10;
echo $x++ . "<br>"; // Outputs: 10
echo $x . "<br>"; // Outputs: 11
$x = 10;
echo --$x . "<br>"; // Outputs: 9
echo $x . "<br>"; // Outputs: 9
$x = 10;
echo $x-- . "<br>"; // Outputs: 10
echo $x . "<br>"; // Outputs: 9
Output
11
11
10
11
9
9
10
9
Logical Operators
Logical operators are typically used to combine conditional statements.
` ` Or
Operator Name Example Output
Example
<?php
$year = 2024;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0))){
echo "$year is a leap year.";
} else{
echo "$year is not a leap year.";
}
Output
2024 is a leap year.
String Operators
String operators are specifically designed for strings.
Example
<?php
$x = "Hello";
$y = " World!";
echo $x . $y . "<br>"; // Outputs: Hello World!
$x .= $y;
echo $x . "<br>"; // Outputs: Hello World!
Output
HelloWorld!
Hello World!
Array Operators
Array operators are used to compare arrays.
=== Identity $x === True if $x and $y have the same key/value pairs in the same order and of the
$y same types
Example
?php
Output
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
?: Ternary $x = expr1 ? Returns the value of $x. The value of $x is expr2 if expr1
expr2 : expr3 = true. The value of $x is expr3 if expr1 = false
?? Null $x = expr1 ?? Returns the value of $x. The value of $x is expr1 if expr1
coalescing expr2 exists, and is not null. If expr1 does not exist, or is null, the
value of $x is expr2. Introduced in PHP 7
Example
1. <?php
$age = 18;
$result = ($age >= 18) ? "Eligible to vote" : "Not eligible to vote";
echo $result;
?>
Output
Eligible to vote
2.<?php
$name = null;
echo $name ?? "Guest"; // Output: Guest
?>
Output
Guest
Using Conditional Statements -If(), else if() and else if condition Statement -Switch() Statements
PHP allows us to perform actions based on some type of conditions that may be logical or
comparative. Based on the result of these conditions i.e., either TRUE or FALSE, an action
would be performed as asked by the user. It’s just like a two- way path. If you want something
then go this way or else turn that way. To use this feature, PHP provides us with four conditional
statements:
if statement
if…else statement
if…elseif…else statement
switch statement
PHP If Statement
If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.
Syntax
f(condition){
//code to be executed
}
Flowchart
Example
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
Output:
If-else statement is slightly different from if statement. It executes one block of code if the
specified condition is true and another block of code if the condition is false.
Syntax
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}
Flowchart
Example
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
Output:
12 is even number
PHP If-else-if Statement
The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we can
check multiple conditions using this statement.
Syntax
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....
} else{
//code to be executed if all given conditions are false
}
Flowchart
Example
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>
Output:
B Grade
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works like
PHP if-else-if statement.
Syntax
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
PHP Switch Flowchart
Example
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Output:
number is equal to 20
PHP while loop can be used to traverse set of code like for loop. The while loop executes a block of
code repeatedly until the condition is FALSE. Once the condition gets FALSE, it exits from the body
of loop.
The while loop is also called an Entry control loop because the condition is checked before entering
the loop body. This means that first the condition is checked. If the condition is true, the block of
code will be executed.
Syntax
while(condition){
//code to be executed
}
Example
<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
Output:
1
2
3
4
5
6
7
8
9
10
<?php
$i=1;
while($i<=3){
$j=1;
while($j<=3){
echo "$i $j<br/>";
$j++;
}
$i++;
}
?>
Output:
11
12
13
21
22
23
31
32
33
Syntax
while(true) {
//code to be executed
}
Example
<?php
while (true) {
echo "Hello Javatpoint!";
echo "</br>";
}
?>
Output:
Hello Javatpoint!
Hello Javatpoint!
Hello Javatpoint!
Hello Javatpoint!
.
.
.
.
.
Hello Javatpoint!
Hello Javatpoint!
The PHP do-while loop is used to execute a set of code of the program several times. If you
have to execute the loop at least once and the number of iterations is not even fixed, it is
recommended to use the do-while loop.
Syntax
do{
//code to be executed
}while(condition);
Flowchart
Example
<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>
Output:
1
2
3
4
5
6
7
8
9
10
It should be used if the number of iterations is known otherwise use while loop. This means
for loop is used when you already know how many times you want to execute a block of
code.
It allows users to put all the loop related statements in one place. See in the syntax given
below:
Syntax
initialization - Initialize the loop counter value. The initial value of the for loop is done only
once. This parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes until the
condition is false. If TRUE, the loop execution continues, otherwise the execution of the
loop ends.
Example
<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>
Output:
1
2
3
4
5
6
7
8
9
10
The foreach loop works on elements basis rather than index. It provides an easiest way to
iterate the elements of an array.
Flowchart
Example
<?php
//declare array
$season = array ("Summer", "Winter", "Autumn", "Rainy");
Output:
Summer
Winter
Autumn
Rainy