0% found this document useful (0 votes)
23 views34 pages

WAD 2nd Unit

The document provides an overview of PHP fundamentals, including variables, data types, operators, control statements, and loop statements. It explains how to create and print variables, the different data types supported by PHP, and various string functions. Additionally, it covers the types of operators available in PHP and their usage in performing operations on variables and values.

Uploaded by

ROSELIN ANDREW
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views34 pages

WAD 2nd Unit

The document provides an overview of PHP fundamentals, including variables, data types, operators, control statements, and loop statements. It explains how to create and print variables, the different data types supported by PHP, and various string functions. Additionally, it covers the types of operators available in PHP and their usage in performing operations on variables and values.

Uploaded by

ROSELIN ANDREW
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Unit-2.

0: Building block of PHP


2.1 Variable, datatype, operator
2.1.1 Creating& Printing Variables
2.1.2 different datatype: integer, float,string, Boolean, array, object
2.1.3 String library function:strrev(),strlen(), strword_count(), strops(),strreplace(),
explode(),implode()
2.1.3 Type of operator: arithmetic,logical, assignment,increment/decrement, string
2.2 Control Statements
2.2.1 if, if- else, if-elseif statements
2.2.2 Switch statement.
2.3 Loop Statements
2.3.1 while, do while statements
2.3.2 for, foreach statements
PHP Variables
In PHP, a variable is declared using a $ sign followed by the variable name.
Here, some important points to know about variables:

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 of declaring a variable in PHP is given below:

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

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:

1. Scalar Types (predefined)


2. Compound Types (user-defined)
3. Special Types
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:

1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes); //the var_dump() function returns the datatype and v
alues
4. echo "</br>";
5. echo "Array Element1: $bikes[0] </br>";
6. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?>
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; //it will not give any output
?>
Output:

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;//+ is the operator and 10,20 are operands


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:

o Arithmetic Operators
o Assignment Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators
We can also categorize operators on behalf of operands. They can be
categorized in 3 forms:
Advertisement

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


o Binary Operators: works on two operands such as binary +, -, *, /
etc.
o 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

Difference of
- Subtraction $a - $b
operands

Product of
* Multiplication $a * $b
operands

Quotient of
/ Division $a / $b
operands

Remainder of
% Modulus $a % $b
operands

$a raised to the
** Exponentiation $a ** $b
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 "=".

Operator Name Example Explanation

The value of right


operand is
= Assign $a = $b
assigned to the
left operand.

Addition same as
+= Add then Assign $a += $b
$a = $a + $b

Subtract then Subtraction same


-= $a -= $b
Assign as $a = $a - $b

Multiplication
Multiply then
*= $a *= $b same as $a = $a
Assign
* $b

Divide then Find quotient


/= Assign $a /= $b same as $a = $a /
(quotient) $b

Divide then Find remainder


%= Assign $a %= $b same as $a = $a
(remainder) % $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 the value of


++$a $a by one, then return
$a
++ Increment
Return $a, then
$a++ increment the value of
$a by one

Decrement the value


--$a of $a by one, then
return $a
-- decrement
Return $a, then
$a-- 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 Name Example Explanation

Return TRUE if
and And $a and $b both $a and $b
are true

Return TRUE if
Or Or $a or $b either $a or $b is
true

Return TRUE if
xor Xor $a xor $b either $ or $b is
true but not both

Return TRUE if
! Not ! $a
$a is not true

Return TRUE if
&& And $a && $b either $a and $b
are true

Return TRUE if
|| Or $a || $b 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

Concatenate both
. Concatenation $a . $b
$a and $b

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

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

1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>
Output:

string is: hello string


integer is: 200
float is: 44.6

PHP Variable: Sum of two variables


File: variable2.php

1. <?php
2. $x=5;
3. $y=6;
4. $z=$x+$y;
5. echo $z;
6. ?>
Output:

11

PHP Variable: case sensitive


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

strrev() :-
The strrev() function is predefined function of PHP. It is used to reverse a string.
It is one of the most basic string operations which are used by programmers and
developers.

Syntax:
string strrev ( string $string );

Example 1
1. <?php
2. $var1="Hello PHP";
3. echo "Your Number is:".$var1;
4. echo "<br>";
5. echo "By using 'strrev()' function:".strrev("$var1");
6. ?>
Output:

Your Number is:Hello PHP


By using 'strrev()' function:PHP olleH

strlen():-
The strlen() function is predefined function of PHP. It is used to find the length of
string or returns the length of a string including all the whitespaces and special
character.

Syntax:
1. strlen(string);

Example 1
1. <?php
2. $str = 'Javatpoint';
3. echo "Your String is:".$str;
4. echo "<br>";
5. echo "By using 'strlen()' function:".strlen($str); // 10
6. ?>
Output:

Your String is:Javatpoint


By using 'strlen()' function:10

str_word_count():-

The str_word_count() is in-built function of PHP. It is used to return information


about words used in a string or counts the number of words in a string.

Syntax:
1. str_word_count(string,return,char)

Example 1
1. <?php
2. $str="PHP Javatpoint";
3. echo "Your string is:".$str;
4. echo "<br>";
5. echo "By using str_word_count(): ".str_word_count($str);
6. ?>
Output:

Your string is:PHP Javatpoint


By using str_word_count(): 2
strops():

The strops() is in-built function of PHP. It is used to find the position of the first
occurrence of a string inside another string or substring in a string.

Syntax:
1. int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] );

Example 1
1. <?php
2. $str1="Hello Php";
3. $str2="Hello Php javatpoint!";
4. echo "First string is: ".$str1;
5. echo "<br>";
6. echo "First string is: ".$str2;
7. echo "<br>";
8. echo "By using 'strpos()' function:".strpos("$str1,$str2","php");
9. //$str1 and $str2 'Php'first letter is upper case so output is nothing.
10. // It is case-sensitive
11. ?>
Output:

First string is: Hello Php


First string is: Hello Php javatpoint!
By using 'strpos()' function:

Example 2
1. <?php
2. $str1="Hello php";
3. $str2=" Hello php javatpoint!";
4. echo "First string is: ".$str1;
5. echo "<br>";
6. echo "First string is: ".$str2;
7. echo "<br>";
8. echo "By using 'strpos()' function:".strpos("$str1,$str2","php");
9. //Find the position of the first occurrence of "php" inside the string
10. ?>
Output:
First string is: Hello php
First string is: Hello php javatpoint!
By using 'strpos()' function:6

str_replace() :

The str_replace() function is a case-sensitive, built-in function of PHP which


replaces some character of the string with other characters. It is used to replace
all the occurrences of the search string with the replacement string.

Syntax
The syntax of the str_replace() function is given below, which has the following
four parameters.

1. str_replace ( $search, $replace, $string, $count)


Example 1: Basic example with string variable

1. <?php
2. $string = "Hii everyone!";
3. $search = 'Hii';
4. $replace = 'Hello';
5. echo '<b>'."String before replacement:".'</br></b>';
6. echo $string.'</br>';
7. $newstr = str_replace($search, $replace, $string, $count);
8. echo '<b>'."New replaced string is:".'</br></b>';
9. echo $newstr.'</br>';
10. echo 'Number of replacement ='.$count;
11. ?>
Output:

In the above example, we can see that "Hii" is replaced with "Hello" and the
number of replacement is only 1.

String before replacement:


Hii everyone!
New replaced string is:
Hello everyone!
Number of replacement = 1
explode():-
PHP explode() is a string function, which splits a string by a string. In simple words, we
can say that it breaks a string into an array. The explode() function has a "separator"
parameter, which cannot contain an empty string, because it holds the original string that
is to be split. It is a binary-safe function.

The explode() function returns an array of strings created by splitting the original string.

Syntax:
1. explode (string $separator, string $originalString, int $limit)

Parameters
There are three parameters passed in the explode() function, in which two parameters
are mandatory, and the last one is optional to pass. These parameters are as follows:

$separator:

This parameter specifies the character for the point at which the original string will split.
In simple words, we can say that whenever this character is found in the string, the string
will be divided into parts.

$originalString:

This parameter holds the string which is to be split into array.

$limit:

The $limit parameter specifies the number of array elements to be returned. It can
contain any integer value (zero, positive, or negative).

Possible values for $limit:

If this parameter contains a positive value, this


Positive
function returns an array of string, split into a
(Greater than 0)
size defined in the $limit parameter.

If the $limit parameter consists of the negative


Negative
value, elements from the last will be trimmed,
(Less than 0)
and the remaining will be returned.

If zero (0) is passed in $limit parameter, it will


Zero return the whole string as a single array
element.
Note: Remember that, if the $limit parameter is not provided in explode() function, the returned
array will contain all elements of string separated by the $separator string.

Return Value
This function returns an array of strings. This array of string is formed by splitting the
original string.

Example 1: Array with $limit parameter

1. <?php
2. // original string
3. $Original_str = "Hello, we are here to help you.";
4.
5. // Passed zero
6. print_r (explode (" ",$Original_str, 0));
7. // Passed positive value
8. print_r (explode (" ",$Original_str, 4));
9. // Passed negative value
10. print_r (explode (" ",$Original_str, -3));
11. ?>
Output:

In the above example, a space character is used as separator to split the string.

Array ( [0] => Hello, we are here to help you. ) Array ( [0] => Hello, [1] => we [2] => are [3] => here
to help you. ) Array ( [0] => Hello, [1] => we [2] => are [3] => here )

The above output can be seen as to better understand:

Array (
[0] => Hello, we are here to help you.
) Array (
[0] => Hello,
[1] => we
[2] => are
[3] => here to help you.
) Array (
[0] => Hello,
[1] => we
[2] => are
[3] => here
)

Example 1: Array without $limit parameter

1. <?php
2. // original string
3. $Original_str = "Hello, welcome to javatpoint.";
4. //without passing optional parameter
5. print_r (explode (" ", $Original_str));
6. ?>
Output:

In the above code, we do not pass the optional parameter, i.e., $limit. Therefore, the
explode() function splits the string into array for different indexes.

Array ( [0] => Hello, [1] => welcome [2] => to [3] => javatpoint. )

Example 3:

1. <?php
2. // original string
3. $Original_str = "Hello, welcome to javatpoint.";
4. //without passing optional parameter
5. print_r (explode ("e", $Original_str));
6. ?>
Output:

In the above code, we used the "e" character to split the string into an array. So,
wherever the "e" is found, the string will be split.

Array ( [0] => H [1] => llo, w [2] => lcom [3] => to javatpoint. )

implode() :
PHP implode() is a string function, which joins the array elements in a string. It is
a binary-safe function. In implode() function, parameters can be passed in any order.

The implode() function works same as the join() function and returns a string created
from the elements of the array. Basically, this function joins all elements of array in one
string.

Syntax
There are two syntax are available for implode() function, which are given below:

implode (string $glue, array $pieces)


or
implode (array $pieces)
Parameters
There are two parameters can be passed in the implode() function, one of which
is mandatory, and another one is optional. These parameters are as follows:

$glue (optional):

It is an optional and string type of parameter. It contains the value to join the
array elements and form a string. Basically, $glue is used to join the string.

$pieces (mandatory):

This parameter contains the array of string to implode. The array elements are
mandatory to pass in implode() function to join into one string.

Return Value
The implode() function returns the string formed from the array elements. The
string will be formed in the same order as elements passed into array. The return
type of this function is string.

Example 1:

In the below example, array elements are joined with + operator using implode()
function.

1. <?php
2. echo "Before using 'implode()' function: <br>";
3. echo "array('Welcome', 'to', 'PHP', 'tutorial') <br> <br>";
4.
5. //store array element in a variable
6. $arr = array('Welcome', 'to', 'PHP', 'tutorial');
7.
8. //join array elements in a string by + operator
9. echo "After using 'implode()' function: <br>";
10. echo implode("+",$arr);
11. ?>
Output:

Before using 'implode()' function:


array('Welcome', 'to', 'PHP', 'tutorial')

After using 'implode()' function:


Welcome+to+PHP+tutorial
PHP If Else
PHP if else statement is used to test condition. There are various ways to use if
statement in PHP.

o if
o if-else
o if-else-if
o 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

1. if(condition){
2. //code to be executed
3. }
Flowchart
Example

1. <?php
2. $num=12;
3. if($num<100){
4. echo "$num is less than 100";
5. }
6. ?>
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

1. if(condition){
2. //code to be executed if true
3. }else{
4. //code to be executed if false
5. }
Flowchart
1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
8. ?>
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

1. if (condition1){
2. //code to be executed if condition1 is true
3. } elseif (condition2){
4. //code to be executed if condition2 is true
5. } elseif (condition3){
6. //code to be executed if condition3 is true
7. ....
8. } else{
9. //code to be executed if all given conditions are false
10. }
Flowchart
Example

1. <?php
2. $marks=69;
3. if ($marks<33){
4. echo "fail";
5. }
6. else if ($marks>=34 && $marks<50) {
7. echo "D grade";
8. }
9. else if ($marks>=50 && $marks<65) {
10. echo "C grade";
11. }
12. else if ($marks>=65 && $marks<80) {
13. echo "B grade";
14. }
15. else if ($marks>=80 && $marks<90) {
16. echo "A grade";
17. }
18. else if ($marks>=90 && $marks<100) {
19. echo "A+ grade";
20. }
21. else {
22. echo "Invalid input";
23. }
24. ?>
Output:

B Grade

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

1. if (condition) {
2. //code to be executed if condition is true
3. if (condition) {
4. //code to be executed if condition is true
5. }
6. }
Flowchart

Example

1. <?php
2. $age = 23;
3. $nationality = "Indian";
4. //applying conditions on nationality and age
5. if ($nationality == "Indian")
6. {
7. if ($age >= 18) {
8. echo "Eligible to give vote";
9. }
10. else {
11. echo "Not eligible to give vote";
12. }
13. }
14. ?>
Output:

Eligible to give vote

PHP Switch Example

1. <?php
2. $a = 34; $b = 56; $c = 45;
3. if ($a < $b) {
4. if ($a < $c) {
5. echo "$a is smaller than $b and $c";
6. }
7. }
8. ?>
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
1. switch(expression){
2. case value1:
3. //code to be executed
4. break;
5. case value2:
6. //code to be executed
7. break;
8. ......
9. default:
10. code to be executed if all cases are not matched;
11. }

Important points to be noticed about switch case:


1. The default is an optional statement. Even it is not important, that default must
always be the last statement.
2. There can be only one default in a switch statement. More than one default may
lead to a Fatal error.
3. Each case can have a break statement, which is used to terminate the sequence
of statement.
4. The break statement is optional to use in switch. If break is not used, all the
statements will execute after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in switch
expression.
6. Nesting of switch statements is allowed, but it makes the program more complex
and less readable.
7. 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:
number is equal to 20

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
1. for(initialization; condition; increment/decrement){
2. //code to be executed
3. }

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

Advertisement

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
1. <?php
2. for($n=1;$n<=10;$n++){
3. echo "$n<br/>";
4. }
5. ?>
Output:

1
2
3
4
5
6
7
8
9
10

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

1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){
4. echo "$i $j<br/>";
5. }
6. }
7. ?>

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

1. foreach( $array as $var ){


2. //code to be executed
3. }
4. ?>
Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. foreach( $season as $arr ){
4. echo "Season is: $arr<br />";
5. }
6. ?>
Output:

Season is: summer


Season is: winter
Season is: spring
Season is: autumn

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
1. while(condition){
2. //code to be executed
3. }

Alternative Syntax
1. while(condition):
2. //code to be executed
3.
4. endwhile;
PHP While Loop Flowchart

PHP While Loop Example


1. <?php
2. $n=1;
3. while($n<=10){
4. echo "$n<br/>";
5. $n++;
6. }
7. ?>
Output:

1
2
3
4
5
6
7
8
9
10

Alternative Example
1. <?php
2. $n=1;
3. while($n<=10):
4. echo "$n<br/>";
5. $n++;
6. endwhile;
7. ?>
Output:

1
2
3
4
5
6
7
8
9

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
1. do{
2. //code to be executed
3. }while(condition);
Flowchart

Example
1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>
Output:

1
2
3
4
5
6
7
8
9
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.
1. <?php
2. $x = 5;
3. do {
4. echo "Welcome to javatpoint! </br>";
5. $x++;
6. } while ($x < 10);
7. ?>
Output:

Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!

User input in PHP


Readline():-
The readline() function is an inbuilt function in PHP that is used to read user input
from the command line window. It provides a way to interactively prompt the user
for input and capture their response as a string.
Syntax:
readline($prompt): string|false
Parameters: This function accepts one parameter which is described below.
 $prompt: This is an optional parameter. This is the string parameter that is
displayed when the user entered the command line interface.
Return Value: The readline() function returns the provided string. This function will
return false if no more data is found to be read.

Program 1: The following program demonstrates the readline() function.

<?php
// Simple example prompting the user for their name
$name = readline("Enter your name: ");

// Check if the user provided a name


if ($name !== "") {
echo "Hello, $name! Nice to meet you.";
} else {
echo "You didn't enter your name.";
}
?>

Output
Enter your name: Hello, ! Nice to meet you.

You might also like