0% found this document useful (0 votes)
4 views

Unit 2 PHP

This document provides an introduction to PHP variables, including their definition, syntax, and rules for declaration. It covers various data types in PHP, including scalar, compound, and special types, and explains operators used in PHP for arithmetic, assignment, comparison, increment/decrement, logical operations, and more. Additionally, it discusses PHP constants and magic constants, along with examples to illustrate their usage.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit 2 PHP

This document provides an introduction to PHP variables, including their definition, syntax, and rules for declaration. It covers various data types in PHP, including scalar, compound, and special types, and explains operators used in PHP for arithmetic, assignment, comparison, increment/decrement, logical operations, and more. Additionally, it discusses PHP constants and magic constants, along with examples to illustrate their usage.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Unit 2

Introduction to PHP Variable

Definition

A variable in PHP is a container used to store data. It starts with a dollar sign ($),
followed by the variable name.

o As PHP is a loosely typed language, so we do not need to declare the data


types of the variables. It automatically analyzes the values and makes
conversions to its correct datatype.
o After declaring a variable, it can be reused throughout the code.
o Assignment Operator (=) is used to assign the value to a variable.

Syntax

$variablename=value;

Rules for declaring PHP variable:

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:

string is: hello string


integer is: 200
float is: 44.6

Example 2

<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
Output:

11

Understanding Data Types

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. Scalar Types (predefined)


2. Compound Types (user-defined)
3. Special Types
PHP Data Types: Scalar Types
It holds only single value. There are 4 scalar data types in PHP.

1. boolean
2. integer
3. float
4. string

PHP Data Types: Compound Types


It can hold multiple values. There are 2 compound data types in PHP.

1. array
2. object

PHP Data Types: Special Types


There are 2 special data types in PHP.

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:

This condition is TRUE.

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.

Rules for integer:

o An integer can be either positive or negative.


o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -
2^31 to 2^31.

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:

Addition of floating numbers: 73.812

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:

Bike Model: Royal Enfield

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.

define(name, value, case-insensitive)

Example
<?php
define("MESSAGE","Hello JavaTpoint PHP");
echo MESSAGE;
?>
Output:
Hello JavaTpoint PHP

PHP constant: const keyword


PHP introduced a keyword const to create a constant. The const keyword defines
constants at compile time. It is a language construct, not a function. The constant
defined using const keyword are case-sensitive.

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

__LINE__ - Returns the current line number in the script.


__FILE__ - Returns the full path and filename of the file.
__DIR__ - Returns the directory of the file.
__FUNCTION__ - Returns the name of the current function.
__CLASS__ - Returns the name of the current class (with namespace, if any).
__TRAIT__ - Returns the name of the current trait (with namespace, if any).
__METHOD__ - Returns the name of the current class method.
__NAMESPACE__ - Returns the name of the current namespace.
ClassName::class - Returns the fully qualified class name as a string.

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.

PHP operators are grouped as follows:

 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

+ 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

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

Assignment operators are used to assign values to variables.

Operator Name Example Output

= Assign $x = $y The left operand gets set to the value of the expression
on the right

+= Add and assign $x += Addition


$y

-= Subtract and assign $x -= $y Subtraction

*= Multiply and assign $x *= $y Multiplication

/= Divide and assign $x /= $y Division


quotient

%= Divide and assign Modulus


modulus

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.

Operator Name Example Output

== Equal $x == $y True if $x is equal to $y

=== Identical $x === $y True if $x is equal to $y, and they are of the same type

!= Not equal $x != $y True if $x is not equal to $y


Operator Name Example Output

<> Not equal $x <> $y True if $x is not equal to $y

!== Not identical $x !== $y True if $x is not equal to $y, or they are not of the same type

< Less than $x < $y True if $x is less than $y

> Greater than $x > $y True if $x is greater than $y

>= Greater than or equal to $x >= $y True if $x is greater than or equal to $y

<= Less than or equal to $x <= $y True if $x is less than or equal to $y

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)

Increment / Decrement Operators


Increment operators are used to increment a variable's value while decrement operators
are used to decrement.

Operator Name Output

++$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

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.

Operator Name Example Output

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
Operator Name Example Output

! Not !$x true if $x is not true

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.

Operator Name Example Output

. Concatenation $str1 . $str2 Concatenation of $str1 and $str2

.= Concatenation assignment $str1 .= $str2 Appends the $str2 to the $str1

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.

Operator Name Example Output

+ Union $x + $y Union of $x and $y

== Equality $x == $y True if $x and $y have the same key/value pairs

=== Identity $x === True if $x and $y have the same key/value pairs in the same order and of the
$y same types

!= Inequality $x != $y True if $x is not equal to $y

<> Inequality $x <> $y True if $x is not equal to $y

!== Non- $x !== $y True if $x is not identical to $y


identity

Example
?php

$x = array("a" => "Red", "b" => "Green", "c" => "Blue");


$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z);
echo "<br>";
var_dump($x == $y); // Outputs: boolean false
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 true
echo "<br>";
var_dump($x !== $y); // Outputs: boolean true
echo "<br>";

Output
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)

Conditional Assignment Operators

Conditional assignment operators are used to set a value depending on conditions.

Operator Name Example Output

?: 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

PHP if statement allows conditional execution of code. It is executed if condition is true.

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:

12 is less than 100


PHP If-else Statement

PHP if-else statement is executed whether condition is true or false.

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

Using the while() Loop -Using the for() Loop

PHP While Loop

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.

It should be used if the number of iterations is not known.

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
}

PHP While Loop Flowchart

Example
<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
Output:

1
2
3
4
5
6
7
8
9
10

PHP Nested While Loop


We can use while loop inside another while loop in PHP, it is known as nested while loop.

<?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

PHP Infinite While Loop


If we pass TRUE in while loop, it will be an infinite loop.

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!

PHP do-while loop


PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-
while loop is guaranteed to run at least once.

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

PHP For Loop


PHP for loop can be used to traverse set of code for the specified number of times.

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

for(initialization; condition; increment/decrement){


//code to be executed
}

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.

Increment/decrement - It increments or decrements the value of the variable.


Flowchart

Example
<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>

Output:

1
2
3
4
5
6
7
8
9
10

PHP foreach loop


The foreach loop is used to traverse the array elements. It works only on array and object. It
will issue an error if you try to use it with the variables of different datatype.

The foreach loop works on elements basis rather than index. It provides an easiest way to
iterate the elements of an array.

In foreach loop, we don't need to increment the value.


Syntax

foreach ($array as $value) {


//code to be executed
}

Flowchart

Example

<?php
//declare array
$season = array ("Summer", "Winter", "Autumn", "Rainy");

//access array elements using foreach loop


foreach ($season as $element) {
echo "$element";
echo "</br>";
}
?>

Output:

Summer
Winter
Autumn
Rainy

You might also like