PHP Nontes
PHP Nontes
With PHP you are not limited to output HTML. You can output images, PDF files,
and even Flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free. Download it from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
#PHP Features
There are given many features of PHP.
o Performance: Script written in PHP executes much faster than those scripts written
in other languages such as JSP & ASP.
o Open Source Software: PHP source code is free available on the web; you can
develop all the version of PHP according to your requirement without paying any
cost.
o Platform Independent: PHP are available for WINDOWS, MAC, LINUX & UNIX
operating system. A PHP application developed in one OS can be easily executed in
other OS also.
o Compatibility: PHP is compatible with almost all local servers used today like
Apache, IIS etc.
o Embedded: PHP code can be easily embedded within HTML tags and script.
Install PHP
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It is
available for all operating systems. There are many AMP options available in the market that
are given below:
If you are on Windows and don't want Perl and other features of XAMPP, you should go for
WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh.
PHP 5 Syntax
A PHP script is executed on the server, and the plain HTML result is sent back
to the browser.
<?php
// PHP code goes here
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a
built-in PHP function "echo" to output the text "Hello World!" on a web page:
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
PHP Case Sensitivity
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-
defined functions are NOT case-sensitive.
In the example below, all three echo statements below are legal (and equal):
Example
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
In the example below, only the first statement will display the value of the
$color variable (this is because $color, $COLOR, and $coLOR are treated as
three different variables):
Example
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
The differences are small: echo has no return value while print has a return
value of 1 so it can be used in expressions. echo can take multiple parameters
(although such usage is rare) while print can take one argument. echo is
marginally faster than print.
PHP Echo
PHP echo is a language construct not a function, so you don't need to use parenthesis with
it. But if you want to use more than one parameters, it is required to use parenthesis.
PHP echo statement can be used to print string, multi line strings, escaping characters,
variable, array etc.
1. <?php
2. echo "Hello by PHP echo";
3. ?>
Output:
Output:
Hello by PHP echo this is multi line text printed by PHP echo statement
Output:
Output:
PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with
the argument list. Unlike echo, it always returns 1.
PHP print statement can be used to print string, multi line strings, escaping characters,
variable, array etc.
1. <?php
2. print "Hello by PHP print ";
3. print ("Hello by PHP print()");
4. ?>
Output:
1. <?php
2. print "Hello by PHP print
3. this is multi line
4. text printed by
5. PHP print statement
6. ";
7. ?>
Output:
Hello by PHP print this is multi line text printed by PHP print statement
1. <?php
2. print "Hello escape \"sequence\" characters by PHP print";
3. ?>
Output:
1. <?php
2. $msg="Hello print() in PHP";
3. print "Message is: $msg";
4. ?>
Output:
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different
variables)
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
The following example will produce the same output as the example above:
Example
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
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:
File: variable3.php
1. <?php
2. $color="red";
3. echo "My car is " . $color . "<br>";
4. echo "My house is " . $COLOR . "<br>";
5. echo "My boat is " . $coLOR . "<br>";
6. ?>
7. <?php
8. $4c="hello";//number (invalid)
9. $*d="hello";//special symbol (invalid)
10.
11. echo "$4c <br/> $*d";
12. ?>
PHP automatically converts the variable to the correct data type, depending on
its value.
In other languages such as C, C++, and Java, the programmer must declare the
name and type of the variable before using it.
The scope of a variable is the part of the script where the variable can be
referenced/used.
PHP has three different variable scopes:
local
global
static
Example
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function:
Example
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
You can have local variables with the same name in different functions, because local variables
are only recognized by the function in which they are declared.
PHP The global Keyword
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the
variable. This array is also accessible from within functions and can be used to update global variables
directly.
Example
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
PHP The Static Keyword
Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.
The $$var (double dollar) is a reference variable that stores the value of the $variable
inside it.
Example 1
1. <?php
2. $x = "abc";
3. $$x = 200;
4. echo $x."<br/>";
5. echo $$x."<br/>";
6. 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.
Example2
1. <?php
2. $x="U.P";
3. $$x="Lucknow";
4. echo $x. "<br>";
5. echo $$x. "<br>";
6. echo "Capital of $x is " . $$x;
7. ?>
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.
Example3
1. <?php
2. $name="Cat";
3. ${$name}="Dog";
4. ${${$name}}="Monkey";
5. echo $name. "<br>";
6. echo ${$name}. "<br>";
7. echo $Cat. "<br>";
8. echo ${${$name}}. "<br>";
9. echo $Dog. "<br>";
10. ?>
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.
Now we have printed the values as $name, ${$name}, $Cat, ${${$name}} and $Dog.
PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the
script. PHP constants can be defined by 2 ways:
PHP constants follow the same PHP variable rules. For example, it can be started with
letter or underscore only.
File: constant1.php
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP");
3. echo MESSAGE;
4. ?>
Output:
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
3. echo MESSAGE;
4. echo message; ?>
Output:
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>
Output:
File: constant4.php
1. <?php
2. const MESSAGE="Hello const by JavaTpoint PHP";
3. echo MESSAGE;
4. ?>
Output:
They are similar to other predefined constants but as they change their values with the
context, they are called magic constants.
There are eight magical constants defined in the below table. They are case-insensitive.
Name Description
__FILE__ Represents full path and file name of the file. If it is used inside an include,
name of included file is returned.
__FUNCTION__ Represents the function name where it is used. If it is used outside of any
function, then it will return blank.
__CLASS__ Represents the class name where it is used. If it is used outside of any
function, then it will return blank.
__TRAIT__ Represents the trait name where it is used. If it is used outside of any
function, then it will return blank. It includes namespace it was declared in.
__METHOD__ Represents the name of the class method where it is used. The method
name is returned as it was declared.
1. <?php
2. echo "<h3>Example for __LINE__</h3>";
3. echo "You are at line number " . __LINE__ . "<br><br>";// print Your current line number i.e;
3
4. echo "<h3>Example for __FILE__</h3>";
5. echo __FILE__ . "<br><br>";//print full path of file with .php extension
6. echo "<h3>Example for __DIR__</h3>";
7. echo __DIR__ . "<br><br>";//print full path of directory where script will be placed
8. echo dirname(__FILE__) . "<br><br>"; //its output is equivalent to above one.
9. echo "<h3>Example for __FUNCTION__</h3>";
10. //Using magic constant inside function.
11. function cash(){
12. echo 'the function name is '. __FUNCTION__ . "<br><br>";//the function name is cash.
13. }
14. cash();
15. //Using magic constant outside function gives the blank output.
16. function test_function(){
17. echo 'HYIIII';
18. }
19. test_function();
20. echo __FUNCTION__ . "<br><br>";//gives the blank output.
21.
22. echo "<h3>Example for __CLASS__</h3>";
23. class abc
24. {
25. public function __construct() {
26. ;
27. }
28. function abc_method(){
29. echo __CLASS__ . "<br><br>";//print name of the class abc.
30. }
31. }
32. $t = new abc;
33. $t->abc_method();
34. class first{
35. function test_first(){
36. echo __CLASS__;//will always print parent class which is first here.
37. }
38. }
39. class second extends first
40. {
41. public function __construct() {
42. ;
43. }
44. }
45. $t = new second;
46. $t->test_first();
47. echo "<h3>Example for __TRAIT__</h3>";
48. trait created_trait{
49. function abc(){
50. echo __TRAIT__;//will print name of the trait created_trait
51. }
52. }
53. class anew{
54. use created_trait;
55. }
56. $a = new anew;
57. $a->abc();
58. echo "<h3>Example for __METHOD__</h3>";
59. class meth{
60. public function __construct() {
61. echo __METHOD__ . "<br><br>";//print meth::__construct
62. }
63. public function meth_fun(){
64. echo __METHOD__;//print meth::meth_fun
65. }
66. }
67. $a = new meth;
68. $a->meth_fun();
69.
70. echo "<h3>Example for __NAMESPACE__</h3>";
71. class name{
72. public function __construct() {
73. echo 'This line will be printed on calling namespace';
74. }
75. }
76. $clas_name= __NAMESPACE__ .'\name';
77. $a = new $clas_name; ?>
PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. For example:
In the above example, + is the binary + operator, 10 and 20 are operands and $num is
variable.
o Arithmetic Operators
o Comparison Operators
o Bitwise Operators
o Logical Operators
o String Operators
o Incrementing/Decrementing Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators
o Assignment Operators
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
** arithmetic right
| bitwise OR left
|| logical OR left
?: ternary left
or logical left
1. Scalar Types
2. Compound Types
3. Special Types
1. boolean
2. integer
3. float
4. string
1. array
2. object
1. resource
2. NULL
Boolean
These data types provide output as 0 or 1. In PHP, value of True is one and the value of
False is nothing.
Syntax
1. <?php
2. $foo = True; // assign the value TRUE to $foo
3. ?>
Example 1
1. <?php
2. $a=true;
3. echo $a;
4. ?>
Syntax
1. bool is_bool ( mixed $var )
Example 1
1. <?php
2. $x=false;
3. echo is_bool($x);
4. ?>
Example 2
1. <?php
2. $y=false;
3. if (is_bool($y))
4. echo 'This is a boolean type.';
5. else
6. echo 'This is not a boolean type.';
7. ?>
Integer
This data type holds only numeric values. It stores only whole number with no
fractional component. The range of integers must lie between -2^31 to 2^31.
Syntax
Integers can be defined in decimal(base 10), hexadecimal(base 16), octal(base 8) or
binary(base 2) notation.
Example 1
1. <?php
2. $x=123;
3. echo $x;
4. ?>
Output:
Example 2
1. <?php
2. $a=100;
3. var_dump($a);
4. ?>
Output:
Example 3
1. <?php
2. // decimal base integers
3. $deci1 = 40;
4. $deci2 = 500;
5. // octal base integers
6. $octal1 = 07;
7. // hexadecimal base integers
8. $octal = 0x45;
9. $add = $deci1 + $deci2;
10. echo $add;
11. ?>
Syntax
1. bool is_int (mixed $var)
Example 1
1. <?php
2. $x=123;
3. echo is_int($x);
4. ?>
Example 2
1. <?php
2. $x = 56;
3. $y = "xyz";
4.
5. if (is_int($x))
6. {
7. echo "$x is Integer \n" ;
8. }
9. else
10. {
11. echo "$x is not an Integer \n" ;
12. }
13. if (is_int($y))
14. {
15. echo "$y is Integer \n" ;
16. }
17. else
18. {
19. echo "$y is not Integer \n" ;
20. }
21. ?>
Example 3
1. <?php
2.
3. $check = 12345;
4. if( is_int($check ))
5. {
6. echo $check . " is an int!";
7. }
8. else
9. {
10. echo $check . " is not an int!";
11. }
12. ?>
Float
This data type represents decimal values. The float (floating point number) is a
number with a decimal point or a number in exponential form.
Syntax
1. $a=1.234;
2. $x=1.2e4;
3. $y=7E-10;
Example 1
1. <?php
2. $x=22.41;
3. echo $x;
4. ?>
Example 2
1. <?php
2. $a = 11.365;
3. var_dump($a);
4. ?>
Example 3
1. <?php
2. $a = 6.203;
3. $b = 2.3e4;
4. $c = 7E-10;
5. var_dump($a);
6. var_dump($b);
7. var_dump($c);
8. ?>
PHP is_float Function
By using this function, we can check that the input value is float or not. This function
was introduced in PHP 4.0.
Syntax
1. bool is_float ( mixed $var )
The is_float() function returns TRUE if the var_name is float, otherwise false.
Example 1
1. <?php
2. $x=123.41;
3. echo is_float($x); ?>
Example 2
1. <?php
2. $a=123.41;
3. $b=12;
4. var_dump (is_float($a));
5. var_dump (is_float($b));
6. ?>
Output:
Example 3
1. <?php
2. $var_name=126.56;
3. if (is_float($var_name))
4. echo 'This is a float value.<br>';
5. else
6. echo 'This is not a float value.<br>';
7. var_dump(is_float('javatpoint'));
8. echo '<br>';
9. var_dump(is_float(85));
10. ?>
Precision:
It is a configuration setting in php.ini used to specify a total number of digits
displayed in floating point number.
Compound Types
There are 2 compound data types in PHP.
1. Array
2. Object
Array:
The array is a collection of heterogeneous (dissimilar) data types. PHP is a loosely typed
language that?s why we can store any type of values in arrays.
Normal variable can store single value, array can store multiple values.The array contains
a number of elements, and each element is a combination of element key and element
value.
Example 1
1. <?php
2. $arr= array(10,20,30);
3. print_r($arr);
4. ?>
Example 2
1. <?php
2. $arr= array(10,'sonoo',30);
3. print_r($arr);
4. ?>
Example 3
1. <?php
2. $arr= array(0=>10,2=>'sonoo',3=>30);
3. print_r($arr);
4. ?>
Object:
An object is a data type which accumulates data and information on how to process that
data. An object is a specific instance of a class which delivers as templates for objects.
SYNTAX:
Example 1
1. <?php class vehicle
2. {
3. function car()
4. {
5. echo "Display tata motors";
6. }
7. }
8. $obj1 = new vehicle;
9. $obj1->car();
10. ?>
Example 2
1. <?php
2. class student
3. {
4. function student()
5. {
6. $this->kundan = 100;
7. }
8. }
9. $obj = new student();
10. echo $obj->kundan;
11. ?>
Example 3
1. <?php
2. class greeting
3. {
4. public $str = "Hello javatpoint and SSSIT";
5. function show_greeting()
6. {
7. return $this->str;
8. }
9. }
10. $obj = new greeting;
11. var_dump($obj);
12. ?>
Special Types
There are 2 special data types in PHP
1. Resource
2. Null
Example 2
1. <?php
2. $conn= ftp_connect("127.0.0.1") or die("could not connect");
3. echo $conn;
4. ?>
Example 3
1. <?php
2. $handle = fopen("tpoint.txt", "r");
3. var_dump($handle);
4. echo "<br>";
5. $conn= ftp_connect("127.0.0.1") or die("could not connect");
6. var_dump($conn);
7. ?>
Example 2
1. <?php
2. $a1 = " ";
3. var_dump($a1);
4. echo "<br />";
5. $a2 = null;
6. var_dump($a2);
7. ?>
Example 3
1. <?php
2. $x = NULL;
3. var_dump($x);
4. echo "<br>";
5. $y = "Hello javatpoint!";
6. $y = NULL;
7. var_dump($y);
8. ?>
PHP is_null() function
By using the is_null function, we can check whether the variable is NULL or not. This function was introduced in
4.0.4.
SYNATX:
1. bool is_null ( mixed $var )
The PHP is_null() function returns true if var is null, otherwise false.
Important Note:
Example 1
1. <?php
2. $var1 = TRUE;
3. if (is_null($var1))
4. {
5. echo 'Variable is NULL';
6. }
7. else
8. {
9. echo 'Variable is not NULL';
10. }
11. ?>
Example 2
1. <?php
2. $x= 100;
3. unset($x);
4. echo is_null($x);
5. ?>
Example 3
1. <?php
2. $x = NULL;
3. $y = "\0";
4. is_null($x) ? print_r("True\n") : print_r("False\n");
5. echo "<br/>";
6. is_null($y) ? print_r("True\n") : print_r("False\n");
7. ?>
Control Statement
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 is executed if condition is true.
Syntax
1. if(condition){
2. //code to be executed
3. }
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
Syntax
1. if(condition){
2. //code to be executed if true
3. }else{
4. //code to be executed if false
5. }
Example
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. ?>
Syntax
if (condition) {
//code to be executed if this condition is true;
} elseif (condition) {
//code to be executed if this condition is true;
} else {
//code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is less
than 10, and "Have a good day!" if the current time is less than 20. Otherwise it
will output "Have a good night!":
Example
<?php
$t = date("H");
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. }
1. <?php
2. $num=20;
3. switch($num){
4. case 10:
5. echo("number is equals to 10");
6. break;
7. case 20:
8. echo("number is equal to 20");
9. break;
10. case 30:
11. echo("number is equal to 30");
12. break;
13. default:
14. echo("number is not equal to 10, 20 or 30");
15. }
16. ?>
Output:
number is equal to 20
Ex2.
1. <?php
2. $ch = "B.Tech";
3. switch ($ch)
4. {
5. case "BCA":
6. echo "BCA is 3 years course";
7. break;
8. case "Bsc":
9. echo "Bsc is 3 years course";
10. break;
11. case "B.Tech":
12. echo "B.Tech is 4 years course";
13. break;
14. case "B.Arch":
15. echo "B.Arch is 5 years course";
16. break;
17. default:
18. echo "Wrong Choice";
19. break;
20. }
21. ?>
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.
Syntax
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
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:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
PHP For Each Loop
PHP for each loop is used to traverse array elements.
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. foreach( $season as $arr ){
4. echo "Season is: $arr<br />";
5. }
6. ?>
Output:
PHP Break
PHP break statement breaks the execution of 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.
Syntax
1. jump statement;
2. break;
1. <?php
2. for($i=1;$i<=10;$i++){
3. echo "$i <br/>";
4. if($i==5){
5. break;
6. }
7. }
8. ?>
Output:
1
2
3
4
5
1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){
4. echo "$i $j<br/>";
5. if($i==2 && $j==2){
6. break;
7. }
8. }
9. }
10. ?>
Output:
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
PHP continue statement
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
1. //jump-statement;
2. continue;
Syntax
1. while(condition){
2. //code to be executed
3. }
Alternative Syntax
1. while(condition):
2. //code to be executed
3. endwhile;
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
10
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
1. <?php
2. $i=1;
3. while($i<=3){
4. $j=1;
5. while($j<=3){
6. echo "$i $j<br/>";
7. $j++;
8. }
9. $i++;
10. }
11. ?>
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
It executes the code at least one time always because condition is checked after executing
the code.
Syntax
1. do{
2. //code to be executed
3. }while(condition);
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
PHP Programs
PHP programs are frequently asked in the interview
1) Sum of Digits
Input: 23
Output: 5
Input: 624
Output: 12
2) Even or odd number
Input: 23
Input: 12
3) Prime number
Input: 17
Input: 57
4) Table of number
Input: 2
Output: 2 4 6 8 10 12 14 16 18 20
Input: 5
Output: 5 10 15 20 25 30 35 40 45 50
5) Factorial
Input: 5
Output: 120
Input: 6
Output: 720
6) Armstrong number
Input: 371
Output: armstrong
Input: 342
7) Palindrome number
Input: 121
Input: 113
Write a PHP program to print fibonacci series without using recursion and
using recursion.
Input: 10
Output: 0 1 1 2 3 5 8 13 21 34
9) Reverse Number
Input: 234
Output: 432
Input: amit
Output: tima
Write a PHP program to swap two numbers with and without using third
variable.
First Input: 10
Second Input: 20
Output: 30
First Input: 50
Second Input: 10
Output: 40
Base Input: 10
Height Input: 15
Output: 75
Length Input: 10
Width Input: 20
Output: 200
16) Leap Year
Write a PHP program to find if the given year is leap year or not.
Input: 2000
Input: 2001
Output:
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
Output:
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
Output:
Output:
Output:
Output:
Output:
Output: