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

PHP Introduction2

The document discusses PHP variables. Some key points covered include: - In PHP, variables are declared with a $ sign followed by the variable name. PHP is loosely typed so the data type does not need to be declared. - Variables can store different data types like strings, integers, and floats. - Variables are case-sensitive. - Variables can have local, global, or static scope. Local variables are only accessible within the function they are declared, while global variables can be accessed anywhere and static variables retain their value between function calls. - PHP also supports reference variables declared with $$ which reference the variable name inside them.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

PHP Introduction2

The document discusses PHP variables. Some key points covered include: - In PHP, variables are declared with a $ sign followed by the variable name. PHP is loosely typed so the data type does not need to be declared. - Variables can store different data types like strings, integers, and floats. - Variables are case-sensitive. - Variables can have local, global, or static scope. Local variables are only accessible within the function they are declared, while global variables can be accessed anywhere and static variables retain their value between function calls. - PHP also supports reference variables declared with $$ which reference the variable name inside them.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

PHP VARIABLES

 In PHP, a variable is declared using a $ sign followed by the variable name. Here, some important
points to know about variables:
 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.
 After declaring a variable, it can be reused throughout the code.
 Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:

RULES FOR DECLARING PHP VARIABLE:

 A variable must start with a dollar ($) sign, followed by the variable name.
 It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
 A variable name must start with a letter or underscore (_) character.
 A PHP variable name cannot contain spaces.
 One thing to be kept in mind that the variable name cannot start with a number or special symbols.
 PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.

PHP VARIABLE: DECLARING STRING, INTEGER, AND FLOAT

Let's see the example to store string, integer, and float values in PHP variables.

FILE: VARIABLE1.PHP

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

PHP VARIABLE: SUM OF TWO VARIABLES

File: variable2.php

<?php  

$x=5;  

$y=6;  
$z=$x+$y;  

echo $z;  

?>  

Output:

PHP VARIABLE: CASE SENSITIVE

In PHP, variable names are case sensitive. So variable name "color" is different from Color, COLOR, COLor etc.

File: variable3.php

<?php  

$color="red";  

echo "My car is " . $color . "<br>";  

echo "My house is " . $COLOR . "<br>";  

echo "My boat is " . $coLOR . "<br>";  

?>  

Output:

My car is red

Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4

My house is

Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5

My boat is

PHP VARIABLE: RULES

 PHP variables must start with letter or underscore only.


 PHP variable can't be start with numbers and special symbols.

File: variablevalid.php

<?php  

$a="hello";//letter (valid)  

$_b="hello";//underscore (valid)  

  

echo "$a <br/> $_b";  

?>  

Output:

File: variableinvalid.php

<?php  
$4c="hello";//number (invalid)  

$*d="hello";//special symbol (invalid)  

  

echo "$4c <br/> $*d";  

?>  

Output:

Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE)

or '$' in C:\wamp\www\variableinvalid.php on line 2

PHP: LOOSELY TYPED LANGUAGE

PHP is a loosely typed language, it means PHP automatically converts the variable to its correct data type.

PHP VARIABLE SCOPE -

The scope of a variable is defined as its range in the program under which it can be accessed. In other words,
"The scope of a variable is the portion of the program within which it is defined and can be accessed."

PHP has three types of variable scopes:

 Local variable
 Global variable
 Static variable

LOCAL VARIABLE

 The variables that are declared within a function are called local variables for that function. These
local variables have their scope only in that particular function in which they are declared. This means
that these variables cannot be accessed outside the function, as they have local scope.
 A variable declaration outside the function with the same name is completely different from the
variable declared inside the function. Let's understand the local variables with the help of an example:

FILE: LOCAL_VARIABLE1.PHP

<?php  

    function local_var()  

    {  

        $num = 45;    

        echo "Local variable declared inside the function is: ". $num;  

    }  

    local_var();  

?>  

Output:

Local variable declared inside the function is: 45


FILE: LOCAL_VARIABLE2.PHP

<?php  

    function mytest()  

    {  

        $lang = "PHP";  

        echo "Web development language: " .$lang;  

    }  

    mytest();  

         echo $lang;  

?>  

Output:

Web development language: PHP

Notice: Undefined variable: lang in D:\xampp\htdocs\program\p3.php on line 28

GLOBAL VARIABLE

The global variables are the variables that are declared outside the function. These variables can be accessed
anywhere in the program. To access the global variable within a function, use the GLOBAL keyword before the
variable. However, these variables can be directly accessed or used outside the function without any keyword.
Therefore there is no need to use any keyword to access a global variable outside the function.

Let's understand the global variables with the help of an example:

Example:

FILE: GLOBAL_VARIABLE1.PHP

<?php  

    $name = "Sanaya Sharma";          

    function global_var()  

    {  

        global $name;  

        echo "Variable inside the function: ". $name;  

        echo "</br>";  

    }  

    global_var();  

    echo "Variable outside the function: ". $name;  

?>  

Output:
Variable inside the function: Sanaya Sharma

Variable outside the function: Sanaya Sharma

Note: Without using the global keyword, if you try to access a global variable inside the function, it will
generate an error that the variable is undefined.

FILE: GLOBAL_VARIABLE2.PHP

<?php  

    $name = "Sanaya Sharma";          

    function global_var()  

    {  

        echo "Variable inside the function: ". $name;  

        echo "</br>";  

    }  

    global_var();  

?>  

Output:

Notice: Undefined variable: name in D:\xampp\htdocs\program\p3.php on line 6

VARIABLE INSIDE THE FUNCTION:

 Using $GLOBALS instead of global


 Another way to use the global variable inside the function is predefined $GLOBALS array.

Example:

File: global_variable3.php

<?php  

    $num1 = 5;        

    $num2 = 13;       

    function global_var()  

    {  

            $sum = $GLOBALS['num1'] + $GLOBALS['num2'];  

            echo "Sum of global variables is: " .$sum;  

    }  

    global_var();  

?>  

Output:
Sum of global variables is: 18

 If two variables, local and global, have the same name, then the local variable has higher priority than
the global variable inside the function.

Example:

FILE: GLOBAL_VARIABLE2.PHP

<?php  

    $x = 5;  

    function mytest()  

    {  

        $x = 7;  

        echo "value of x: " .$x;  

    }  

    mytest();  

?>  

Output:

Note: local variable has higher priority than the global variable.

STATIC VARIABLE

 It is a feature of PHP to delete the variable, once it completes its execution and memory is freed.
Sometimes we need to store a variable even after completion of function execution. Therefore,
another important feature of variable scoping is static variable. We use the static keyword before the
variable to define a variable, and this variable is called as static variable.
 Static variables exist only in a local function, but it does not free its memory after the program
execution leaves the scope. Understand it with the help of an example:

Example:

File: static_variable.php

<?php  

    function static_var()  

    {  

        static $num1 = 3;         

        $num2 = 6;            

          

        $num1++;  

          

        $num2++;  
        echo "Static: " .$num1 ."</br>";  

        echo "Non-static: " .$num2 ."</br>";  

    }  

      

  

    static_var();   

    static_var();  

?>  

Output:

Static: 4

Non-static: 7

Static: 5

Non-static: 7

You have to notice that $num1 regularly increments after each function call, whereas $num2 does not. This is
why because $num1 is not a static variable, so it freed its memory after the execution of each function call.

PHP $ AND $$ -

The $var (single dollar) is a normal variable with the name var that stores any value like string, integer, float,
etc.

The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.

To understand the difference better, let's see some examples.

Example 1

<?php  

$x = "abc";  

$$x = 200;  

echo $x."<br/>";  

echo $$x."<br/>";  

echo $abc;  

?>  

Output:
In the above example, we have assigned a value to the variable x as abc. Value of reference variable $$x is
assigned as 200.

Now we have printed the values $x, $$x and $abc.

Example2

<?php  

 $x="U.P";  

$$x="Lucknow";  

echo $x. "<br>";  

echo $$x. "<br>";  

echo "Capital of $x is " . $$x;  

?>  

Output:

In the above example, we have assigned a value to the variable x as U.P. Value of reference variable $$x is
assigned as Lucknow.

Now we have printed the values $x, $$x and a string.

Example3

<?php  

$name="Cat";  

${$name}="Dog";  

${${$name}}="Monkey";  

echo $name. "<br>";  
echo ${$name}. "<br>";  

echo $Cat. "<br>";  

echo ${${$name}}. "<br>";  

echo $Dog. "<br>";  

?>  

Output:

In the above example, we have assigned a value to the variable name Cat. Value of reference variable $
{$name} is assigned as Dog and ${${$name}} as Monkey.

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:

 Using define() function


 Using const keyword

Constants are similar to the variable except once they defined, they can never be undefined or changed. They
remain constant across the entire program. PHP constants follow the same PHP variable rules. For example, it
can be started with a letter or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

Note: Unlike variables, constants are automatically global throughout the script.

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)  

name: It specifies the constant name.

value: It specifies the constant value.

case-insensitive: Specifies whether a constant is case-insensitive. Default value is false. It means it is case
sensitive by default.

Let's see the example to define PHP constant using define().

FILE: CONSTANT1.PHP
<?php  

define("MESSAGE","Hello  PHP");  

echo MESSAGE;  

?>  

Output:

Hello PHP

Create a constant with case-insensitive name:

FILE: CONSTANT2.PHP
<?php    

define("MESSAGE","Hello  PHP",true);//not case sensitive    

echo MESSAGE, "</br>";    

echo message;    

?>    

Output:

Hello PHP

Hello PHP

FILE: CONSTANT3.PHP
<?php  

define("MESSAGE","Hello  PHP",false);//case sensitive  

echo MESSAGE;  

echo message;  

?>  

Output:

Hello PHP

Notice: Use of undefined constant message - assumed 'message'

in C:\wamp\www\vconstant3.php on line 4

message

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.

FILE: CONSTANT4.PHP
<?php  
const MESSAGE="Hello const by  PHP";  

echo MESSAGE;  

?>  

Output:

Hello const by 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)  

FILE: CONSTANT5.PHP
<?php      

    define("MSG", "");  

    echo MSG, "</br>";  

    echo constant("MSG");  

    //both are similar  

?>  

Output:

CONSTANT VS VARIABLES

Constant Variables
Once the constant is defined, it can never be redefined. A variable can be undefined as well as redefined
easily.
A constant can only be defined using define() function. A variable can be defined by simple assignment
It cannot be defined by any simple assignment. (=) operator.
There is no need to use the dollar ($) sign before To declare a variable, always use the dollar ($)
constant during the assignment. sign before the variable.
Constants do not follow any variable scoping rules, and Variables can be declared anywhere in the
they can be defined and accessed anywhere. program, but they follow variable scoping rules.
Constants are the variables whose values can't be The value of the variable can be changed.
changed throughout the program.
By default, constants are global. Variables can be local, global, or static.

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

 Scalar Types (predefined)


 Compound Types (user-defined)
 Special Types

PHP DATA TYPES: SCALAR TYPES

It holds only single value. There are 4 scalar data types in PHP.

 boolean
 integer
 float
 string

PHP DATA TYPES: COMPOUND TYPES

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

 array
 object

PHP DATA TYPES: SPECIAL TYPES

There are 2 special data types in PHP.

 resource
 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.

RULES FOR INTEGER:

 An integer can be either positive or negative.


 An integer must not contain decimal point.
 Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
 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 = "";  

      

    echo "Hello $company";  

    echo "</br>";  

    echo 'Hello $company';  

?>  

Output:

Hello

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);     

    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

You will learn more about array in later chapters of this tutorial.

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

This is an advanced topic of PHP, which we will discuss later in detail.

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;     

?>  

PHP OPERATORS -

PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used to
perform operations on variables or values. For example:

$num=10+20;  

In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.

PHP Operators can be categorized in following forms:

 Arithmetic Operators
 Assignment Operators
 Bitwise Operators
 Comparison Operators
 Incrementing/Decrementing Operators
 Logical Operators
 String Operators
 Array Operators
 Type Operators
 Execution Operators
 Error Control Operators

We can also categorize operators on behalf of operands. They can be categorized in 3 forms:

Unary Operators: works on single operands such as ++, -- etc.

Binary Operators: works on two operands such as binary +, -, *, / etc.

Ternary Operators: works on three operands such as "?:".

ARITHMETIC OPERATORS

The PHP arithmetic operators are used to perform common arithmetic operations such as addition,
subtraction, etc. with numeric values.

Operator Name Example Explanation


+ Addition $a + $b Sum of operands
- Subtraction $a - $b Difference of operands
* Multiplication $a * $b Product of operands
/ Division $a / $b Quotient of operands
% Modulus $a % $b Remainder of operands
** Exponentiation $a ** $b $a raised to the power $b
The exponentiation (**) operator has been introduced in PHP 5.6.

ASSIGNMENT OPERATORS

The assignment operators are used to assign value to different variables. The basic assignment operator is "=".

Operato Name Example Explanation


r
= Assign $a = $b The value of right operand is assigned to the left operand.
+= Add then Assign $a += $b Addition same as $a = $a + $b
-= Subtract then Assign $a -= $b Subtraction same as $a = $a - $b
*= Multiply then Assign $a *= $b Multiplication same as $a = $a * $b
/= Divide then Assign $a /= $b Find quotient same as $a = $a / $b
(quotient)
%= Divide then Assign $a %= $b Find remainder same as $a = $a % $b
(remainder)

BITWISE OPERATORS

The bitwise operators are used to perform bit-level operations on operands. These operators allow the
evaluation and manipulation of specific bits within the integer.

Operator Name Example Explanation


& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0.
| Or (Inclusive or) $a | $b Bits that are 1 in either $a or $b are set to 1
^ Xor (Exclusive or) $a ^ $b Bits that are 1 in either $a or $b are set to 0.
~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places

COMPARISON OPERATORS

Comparison operators allow comparing two values, such as number or string. Below the list of comparison
operators are given:

Operator Name Example Explanation


== Equal $a == $b Return TRUE if $a is equal to $b
=== Identical $a === Return TRUE if $a is equal to $b, and they are of same data
$b type
!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they are not of
same data type
!= Not equal $a != $b Return TRUE if $a is not equal to $b
<> Not equal $a <> $b Return TRUE if $a is not equal to $b
< Less than $a < $b Return TRUE if $a is less than $b
> Greater than $a > $b Return TRUE if $a is greater than $b
<= Less than or equal to $a <= $b Return TRUE if $a is less than or equal $b
>= Greater than or $a >= $b Return TRUE if $a is greater than or equal $b
equal to
<=> Spaceship $a <=>$b Return -1 if $a is less than $b
Return 0 if $a is equal $b
Return 1 if $a is greater than $b

INCREMENTING/DECREMENTING OPERATORS

The increment and decrement operators are used to increase and decrease the value of a variable.

Operator Name Example Explanation


++ Increment ++$a Increment the value of $a by one, then return $a
$a++ Return $a, then increment the value of $a by one
-- decremen --$a Decrement the value of $a by one, then return $a
t
$a-- Return $a, then decrement the value of $a by one

LOGICAL OPERATORS

The logical operators are used to perform bit-level operations on operands. These operators allow the
evaluation and manipulation of specific bits within the integer.

Operator Nam Example Explanation


e
and And $a and $b Return TRUE if both $a and $b are true
Or Or $a or $b Return TRUE if either $a or $b is true
xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
! Not ! $a Return TRUE if $a is not true
&& And $a && $b Return TRUE if either $a and $b are true
|| Or $a || $b Return TRUE if either $a or $b is true

STRING OPERATORS

The string operators are used to perform the operation on strings. There are two string operators in PHP,
which are given below:

Operator Name Example Explanation


. Concatenation $a . $b Concatenate both $a and $b
.= Concatenation and $a .= $b First concatenate $a and $b, then assign the
Assignment concatenated string to $a, e.g. $a = $a . $b

ARRAY OPERATORS

The array operators are used in case of array. Basically, these operators are used to compare the values of
arrays.

Operator Name Example Explanation


+ Union $a + $y Union of $a and $b
== Equality $a == $b Return TRUE if $a and $b have same key/value pair
!= Inequality $a != $b Return TRUE if $a is not equal to $b
=== Identity $a === Return TRUE if $a and $b have same key/value pair of same type in
$b same order
!== Non- $a !== $b Return TRUE if $a is not identical to $b
Identity
<> Inequality $a <> $b Return TRUE if $a is not equal to $b

TYPE OPERATORS

The type operator instanceof is used to determine whether an object, its parent and its derived class are the
same type or not. Basically, this operator determines which certain class the object belongs to. It is used in
object-oriented programming.

<?php  

    //class declaration  

    class Developer  

    {}  

    class Programmer  

    {}  
    //creating an object of type Developer  

    $charu = new Developer();  

      

    //testing the type of object  

    if( $charu instanceof Developer)  

    {  

        echo "Charu is a developer.";  

    }  

    else  

    {     

        echo "Charu is a programmer.";  

    }  

    echo "</br>";  

    var_dump($charu instanceof Developer);           //It will return true.  

    var_dump($charu instanceof Programmer);       //It will return false.  

?>  

Output:

Charu is a developer.

bool(true) bool(false)

EXECUTION OPERATORS

PHP has an execution operator backticks (``). PHP executes the content of backticks as a shell command.
Execution operator and shell_exec() give the same result.

Operato Name Example Explanation


r
`` backticks echo `dir`; Execute the shell command and return the result.
Here, it will show the directories available in current folder.
Note: Note that backticks (``) are not single-quotes.

ERROR CONTROL OPERATORS

PHP has one error control operator, i.e., at (@) symbol. Whenever it is used with an expression, any error
message will be ignored that might be generated by that expression.

Operator Name Example Explanation


@ at @file ('non_existent_file') Intentional file error
PHP OPERATORS PRECEDENCE

Let's see the precedence of PHP operators with associativity.

Operators Additional Information Associativity


clone new clone and new non-associative
[ array() left
** arithmetic right
++ -- ~ (int) (float) (string) (array) (object) (bool) @ increment/decrement and types right
instanceof types non-associative
! logical (negation) right
*/% arithmetic left
+-. arithmetic and string concatenation left
<< >> bitwise (shift) left
< <= > >= comparison non-associative
== != === !== <> comparison non-associative
& bitwise AND left
^ bitwise XOR left
| bitwise OR left
&& logical AND left
|| logical OR left
?: ternary left
= += -= *= **= /= .= %= &= |= ^= <<= >>= => assignment right
and logical left
xor logical left
or logical left
, many uses (comma) left

PHP COMMENTS -

 PHP comments can be used to describe any line of code so that other developer can understand the
code easily. It can also be used to hide any code.
 PHP supports single line and multi line comments. These comments are similar to C/C++ and Perl style
(Unix shell style) comments.

PHP SINGLE LINE COMMENTS

There are two ways to use single line comments in PHP.

// (C++ style single line comment)

# (Unix Shell style single line comment)

<?php  

  
# this is Unix Shell style single line comment  

echo "Welcome to PHP single line comments";  

?>  

Output:

Welcome to PHP single line comments

PHP MULTI LINE COMMENTS

In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within /* */. Let's see a
simple example of PHP multiple line comment.

<?php  

  

echo "Welcome to PHP multi line comment";  

?>  

Output:

Welcome to PHP multi line comment

PHP IF ELSE -

PHP if else statement is used to test condition. There are various ways to use if statement in PHP.

 if
 if-else
 if-else-if
 nested if

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

Flowchart
EXAMPLE
<?php  

$num=12;  

if($num<100){  

echo "$num is less than 100";  

}  

?>  

Output:

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

Flowchart

EXAMPLE
<?php  
$num=12;  

if($num%2==0){  

echo "$num is even number";  

}else{  

echo "$num is odd 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){    

  

} elseif (condition2){      

  

} elseif (condition3){      

  

....  

}  else{    

  

}    

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";    

    }    

?>  

PHP NESTED IF STATEMENT

The nested if statement contains the if block inside another if block. The inner if statement executes only when
specified condition in outer if statement is true.

Syntax

if (condition) {    

  

if (condition) {    

  

}    

}   
Flowchart

EXAMPLE
<?php  

               $age = 23;  

    $nationality = "Indian";  

      

    if ($nationality == "Indian")  

    {  

        if ($age >= 18) {  

            echo "Eligible to give vote";  

        }  

        else {    

            echo "Not eligible to give vote";  

        }  

    }  

?>  

Output:

PHP SWITCH EXAMPLE


<?php  

              $a = 34; $b = 56; $c = 45;  

    if ($a < $b) {  

        if ($a < $c) {  
            echo "$a is smaller than $b and $c";  

        }  

    }  

?>  

Output:

34 is smaller than 56 and 45

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:      

   

 break;  

case value2:      

   

 break;  

......      

default:       

 code to be executed if all cases are not matched;    

}  

IMPORTANT POINTS TO BE NOTICED ABOUT SWITCH CASE:


 The default is an optional statement. Even it is not important, that default must always be the last
statement.
 There can be only one default in a switch statement. More than one default may lead to a Fatal error.
 Each case can have a break statement, which is used to terminate the sequence of statement.
 The break statement is optional to use in switch. If break is not used, all the statements will execute
after finding matched case value.
 PHP allows you to use number, character, string, as well as functions in switch expression.
 Nesting of switch statements is allowed, but it makes the program more complex and less readable.
 You can use semicolon (;) instead of colon (:). It will not generate any error.

PHP SWITCH FLOWCHART


PHP SWITCH 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:

PHP switch statement with character


PROGRAM TO CHECK VOWEL AND CONSONANT
We will pass a character in switch expression to check whether it is vowel or constant. If the passed character
is A, E, I, O, or U, it will be vowel otherwise consonant.

<?php      

    $ch = 'U';  

    switch ($ch)  

    {     

        case 'a':   

            echo "Given character is vowel";  

            break;  

        case 'e':   

            echo "Given character is vowel";  

            break;  

        case 'i':   

            echo "Given character is vowel";  

            break;  

        case 'o':   

            echo "Given character is vowel";  

            break;    

        case 'u':   

            echo "Given character is vowel";  

            break;  

        case 'A':   

            echo "Given character is vowel";  

            break;  

        case 'E':   

            echo "Given character is vowel";  

            break;  

        case 'I':   

            echo "Given character is vowel";  

            break;  

        case 'O':   
            echo "Given character is vowel";  

            break;  

        case 'U':   

            echo "Given character is vowel";  

            break;  

        default:   

            echo "Given character is consonant";  

            break;  

    }  

?>    

PHP SWITCH STATEMENT WITH STRING


PHP allows to pass string in switch expression. Let's see the below example of course duration by passing string
in switch case statement.

<?php      

    $ch = "B.Tech";  

    switch ($ch)  

    {     

        case "BCA":   

            echo "BCA is 3 years course";  

            break;  

        case "Bsc":   

            echo "Bsc is 3 years course";  

            break;  

        case "B.Tech":   

            echo "B.Tech is 4 years course";  

            break;  

        case "B.Arch":   

            echo "B.Arch is 5 years course";  

            break;  

        default:   

            echo "Wrong Choice";  

            break;  
    }  

?>    

Output:

PHP SWITCH STATEMENT IS FALL-THROUGH


PHP switch statement is fall-through. It means it will execute all statements after getting the first match, if
break statement is not found.

<?php      

    $ch = 'c';  

    switch ($ch)  

    {     

        case 'a':   

            echo "Choice a";  

            break;  

        case 'b':   

            echo "Choice b";  

            break;  

        case 'c':   

            echo "Choice c";      

            echo "</br>";  

        case 'd':   

            echo "Choice d";  

            echo "</br>";  

        default:   

            echo "case a, b, c, and d is not found";  

    }  

?>    

Output:

Choice c

Choice d

case a, b, c, and d is not found

PHP NESTED SWITCH STATEMENT


Nested switch statement means switch statement inside another switch statement. Sometimes it leads to
confusion.

<?php      

    $car = "Hyundai";                   

        $model = "Tucson";    

        switch( $car )    

        {    

            case "Honda":    

                switch( $model )     

                {    

                    case "Amaze":    

                           echo "Honda Amaze price is 5.93 - 9.79 Lakh.";   

                        break;    

                    case "City":    

                           echo "Honda City price is 9.91 - 14.31 Lakh.";    

                        break;     

                }    

                break;    

            case "Renault":    

                switch( $model )     

                {    

                    case "Duster":    

                        echo "Renault Duster price is 9.15 - 14.83 L.";  

                        break;    

                    case "Kwid":    

                           echo "Renault Kwid price is 3.15 - 5.44 L.";  

                        break;    

                }    

                break;    

            case "Hyundai":    

                switch( $model )     

                {    
                    case "Creta":    

                        echo "Hyundai Creta price is 11.42 - 18.73 L.";  

                        break;    

        case "Tucson":    

                           echo "Hyundai Tucson price is 22.39 - 32.07 L.";  

                        break;   

                    case "Xcent":    

                           echo "Hyundai Xcent price is 6.5 - 10.05 L.";  

                        break;    

                }    

                break;     

        }  

?>    

Output:

Hyundai Tucson price is 22.39 - 32.07 L.

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){  

  

}  

PARAMETERS

The php for loop is similar to the java/C/C++ for loop. The parameters of for loop have the following meanings:

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

Example

All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don't pass parameters, it
will execute infinite.

<?php  

    $i = 1;  

      

    for (;;) {  

        echo $i++;  

        echo "</br>";  

    }  

?>  

Output:

EXAMPLE
Below is the example of printing numbers from 1 to 9 in four different ways using for loop.

<?php  

      

  

    for ($i = 1; $i <= 9; $i++) {  
    echo $i;  

    }  

    echo "</br>";  

 for ($i = 1; ; $i++) {  

        if ($i > 9) {  

            break;  

        }  

        echo $i;  

    }  

    echo "</br>";  

         $i = 1;  

    for (; ; ) {  

        if ($i > 9) {  

            break;  

        }  

        echo $i;  

        $i++;  

    }  

    echo "</br>";  

   for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++);  

?>  

Output:

123456789

123456789

123456789

123456789

PHP NESTED FOR LOOP

We can use for loop inside for loop in PHP, it is known as nested for loop. The inner for loop executes only
when the outer for loop condition is found true.

In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If outer for loop is
to be executed for 3 times and inner for loop for 3 times, inner for loop will be executed 9 times (3 times for
1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).
EXAMPLE
<?php    

for($i=1;$i<=3;$i++){    

for($j=1;$j<=3;$j++){    

echo "$i   $j<br/>";    

}    

}    

?>  

Output:

11

12

13

21

22

23

31

32

33

PHP FOR EACH LOOP

PHP for each loop is used to traverse array elements.

Syntax

foreach( $array as $var ){  

   

}  

?>  

Example

<?php  

$season=array("summer","winter","spring","autumn");  

foreach( $season as $arr ){  

  echo "Season is: $arr<br />";  

}  

?>  
Output:

Season is: summer

Season is: winter

Season is: spring

Season is: autumn

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) {  

      

}  

There is one more syntax of foreach loop.

Syntax

foreach ($array as $key => $element) {   

      

}  

Flowchart

EXAMPLE 1:
PHP program to print array elements using foreach loop.

<?php  

      

    $season = array ("Summer", "Winter", "Autumn", "Rainy");  
      

      

    foreach ($season as $element) {  

        echo "$element";  

        echo "</br>";  

    }  

?>  

Output:

Summer

Winter

Autumn

Rainy

EXAMPLE 2:
PHP program to print associative array elements using foreach loop.

<?php  

      

    $employee = array (  

        "Name" => "Alex",  

        "Email" => "[email protected]",  

        "Age" => 21,  

        "Gender" => "Male"  

    );  

      

      

    foreach ($employee as $key => $element) {  

        echo $key . " : " . $element;  

        echo "</br>";   

    }  

?>  

Output:

Name : Alex
Email : [email protected]

Age : 21

Gender : Male

EXAMPLE 3:MULTI-DIMENSIONAL ARRAY


<?php  

      

    $a = array();  

    $a[0][0] = "Alex";  

    $a[0][1] = "Bob";  

    $a[1][0] = "Camila";  

    $a[1][1] = "Denial";  

      

      

    foreach ($a as $e1) {  

        foreach ($e1 as $e2) {  

            echo "$e2\n";  

        }  

    }  

?>  

Output:

Example 4:

Dynamic array

<?php  

      

    foreach (array ('j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't') as $elements) {  

        echo "$elements\n";  

    }  

?>  

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

Alternative Syntax

while(condition):  

  

  

endwhile;  

PHP While Loop Flowchart

PHP WHILE LOOP EXAMPLE


<?php    

$n=1;    

while($n<=10){    

echo "$n<br/>";    

$n++;    

}    

?>  

Output:

Alternative Example

<?php    

$n=1;    

while($n<=10):    

echo "$n<br/>";    

$n++;    

endwhile;    

?>    
Output:

Example

PRINTING ALPHABETS USING WHILE LOOP.


<?php  

    $i = 'A';  

    while ($i < 'H') {  

        echo $i;  

        $i++;  

        echo "</br>";  

    }  

?>  

Output:

PHP Nested While Loop

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

In case of inner or nested while loop, nested while loop is executed fully for one outer while loop. If outer
while loop is to be executed for 3 times and nested while loop for 3 times, nested while loop will be executed 9
times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).

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

Example

<?php  

    while (true) {  

        echo "Hello !";  

        echo "</br>";  

    }  

?>  

Output:

Hello !

Hello !

Hello !

Hello !

Hello !

Hello !

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.
 It executes the code at least one time always because the condition is checked after executing the
code.
 The do-while loop is very much similar to the while loop except the condition check. The main
difference between both loops is that while loop checks the condition at the beginning, whereas do-
while loop checks the condition at the end of the loop.

Syntax

do{  

  

}while(condition);  

Flowchart

EXAMPLE
<?php    

$n=1;    

do{    

echo "$n<br/>";    

$n++;    

}while($n<=10);    

?>    

Output:

6
7

10

EXAMPLE
A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the do-while loop, it is
must that the program should not contain any other statements after the do-while loop. In this case, it will not
generate any error.

 <?php  

    $x = 5;  

    do {  

        echo "Welcome to ! </br>";  

        $x++;  

    } while ($x < 10);  

?>  

Output:

Welcome to !

Welcome to !

Welcome to !

Welcome to !

Welcome to !

EXAMPLE
The following example will increment the value of $x at least once. Because the given condition is false.

 <?php  

    $x = 1;  

    do {  

        echo "1 is not greater than 10.";  

        echo "</br>";  

        $x++;  

    } while ($x > 10);  

    echo $x;  

?>  
Output:

1 is not greater than 10.

DIFFERENCE BETWEEN WHILE AND DO-WHILE LOOP

while Loop do-while loop


The while loop is also named as entry control The do-while loop is also named as exit control loop.
loop.
The body of the loop does not execute if the The body of the loop executes at least once, even if the
condition is false. condition is false.
Condition checks first, and then block of Block of statements executes first and then condition
statements executes. checks.
This loop does not use a semicolon to terminate Do-while loop use semicolon to terminate the loop.
the loop.

PHP BREAK -

PHP break statement breaks the execution of the current for, while, do-while, switch, and for-each loop. If you
use break inside inner loop, it breaks the execution of inner loop only.

The break keyword immediately ends the execution of the loop or switch structure. It breaks the current flow
of the program at the specified condition and program control resumes at the next statements outside the
loop.

The break statement can be used in all types of loops such as while, do-while, for, foreach loop, and also with
switch case.

Syntax

Flowchart

PHP BREAK: INSIDE LOOP


Let's see a simple example to break the execution of for loop if value of i is equal to 5.

<?php    

for($i=1;$i<=10;$i++){    

echo "$i <br/>";    

if($i==5){    

break;    
}    

}    

?>  

Output:

PHP BREAK: INSIDE INNER LOOP


The PHP break statement breaks the execution of inner loop only.

<?php    

for($i=1;$i<=3;$i++){    

 for($j=1;$j<=3;$j++){    

  echo "$i   $j<br/>";    

  if($i==2 && $j==2){    

   break;    

  }    

 }    

}    

?>  

Output:

11

12

13

21

22

31

32

33

PHP BREAK: INSIDE SWITCH STATEMENT


The PHP break statement breaks the flow of switch case also.

<?php        

$num=200;        

switch($num){        

case 100:        
echo("number is equals to 100");        

break;        

case 200:        

echo("number is equal to 200");        

break;        

case 50:        

echo("number is equal to 300");        

break;        

default:        

echo("number is not equal to 100, 200 or 500");        

}       

?>  

Output:

PHP BREAK: WITH ARRAY OF STRING


<?php  

  

$number = array ("One", "Two", "Three", "Stop", "Four");  

foreach ($number as $element) {  

if ($element == "Stop") {  

break;  

}  

echo "$element </br>";  

}  

?>  

Output:

You can see in the above output, after getting the specified condition true, break statement immediately ends
the loop and control is came out from the loop.

PHP BREAK: SWITCH STATEMENT WITHOUT BREAK


It is not essential to break out of all cases of a switch statement. But if you want that only one case to be
executed, you have to use break statement.

<?php  

$car = 'Mercedes Benz';  
switch ($car) {    

default:  

echo '$car is not Mercedes Benz<br>';  

case 'Orange':  

echo '$car is Mercedes Benz';  

}  

?>  

Output:

$car is not Mercedes Benz

$car is Mercedes Benz

PHP BREAK: USING OPTIONAL ARGUMENT


The break accepts an optional numeric argument, which describes how many nested structures it will exit. The
default value is 1, which immediately exits from the enclosing structure.

<?php  

$i = 0;  

while (++$i) {  

    switch ($i) {  

        case 5:  

            echo "At matched condition i = 5<br />\n";  

            break 1;    

       case 10:  

            echo "At matched condition i = 10; quitting<br />\n";  

            break 2;    

       default:  

            break;  

    }  

}?>  

Output:

At matched condition i = 5

At matched condition i = 10; quitting

Note: The break keyword immediately ends the execution of the current structure.

PHP CONTINUE -
 The PHP continue statement is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition.
 The continue statement is used within looping and switch control structure when you immediately
jump to the next iteration.
 The continue statement can be used with all types of loops such as - for, while, do-while, and foreach
loop. The continue statement allows the user to skip the execution of the code for the specified
condition.

Syntax

The syntax for the continue statement is given below:

jump-statement;  

continue;  

Flowchart:

PHP Continue Example with for loop

Example

In the following example, we will print only those values of i and j that are same and skip others.

<?php  

      

    for ($i =1; $i<=3; $i++) {  

          

        for ($j=1; $j<=3; $j++) {  

            if (!($i == $j) ) {  

                continue;         

            }  

            echo $i.$j;  

            echo "</br>";  

        }  

    }  
?>  

Output:

PHP continue Example in while loop

EXAMPLE
In the following example, we will print the even numbers between 1 to 20.

<?php  

      

  

    echo "Even numbers between 1 to 20: </br>";  

    $i = 1;  

    while ($i<=20) {  

        if ($i %2 == 1) {  

            $i++;  

            continue;     

        }  

        echo $i;  

        echo "</br>";  

        $i++;  

    }     

?>  

Output:

Even numbers between 1 to 20:

10

12

14

16

18
20

PHP CONTINUE EXAMPLE WITH ARRAY OF STRING


Example

The following example prints the value of array elements except those for which the specified condition is true
and continue statement is used.

<?php  

    $number = array ("One", "Two", "Three", "Stop", "Four");  

    foreach ($number as $element) {  

        if ($element == "Stop") {  

            continue;  

        }  

        echo "$element </br>";  

    }  

?>  

Output:

PHP CONTINUE EXAMPLE WITH OPTIONAL ARGUMENT


The continue statement accepts an optional numeric value, which is used accordingly. The numeric value
describes how many nested structures it will exit.

Example

Look at the below example to understand it better:

<?php        

    for ($i =1; $i<=3; $i++) {            

        for ($j=1; $j<=3; $j++) {  

            if (($i == $j) ) {        

                continue 1;       

            }  

            echo $i.$j;  

            echo "</br>";  

        }  

    }     

?> 

You might also like