PHP Tutorial
PHP Tutorial
PHP Tutorial
PHP tutorial for beginners and professionals provides deep knowledge of PHP scripting
language. Our PHP tutorial will help you to learn PHP scripting language easily. This PHP
tutorial covers all the topics of PHP such as introduction, control statements, functions, array,
string, file handling, form handling, regular expression, date and time, object-oriented
programming in PHP, math, PHP mysql, PHP with ajax, PHP with jquery and PHP with XML.
What is PHP
o PHP stands for HyperText Preprocessor.
o PHP is faster than other scripting language e.g. asp and jsp.
PHP Example
In this tutorial, you will get a lot of PHP examples to understand the topic well. The PHP file
must be save with .php extension. Let's see a simple PHP example.
File: hello.php
1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
5. echo "<h2>Hello by PHP</h2>";
6. ?>
7. </body>
8. </html>
Output:
Hello by PHP
Web Development
PHP is widely used in web development now a days. Dynamic websites can be easily developed
by PHP. But you must have the basic the knowledge of following technologies for web
development as well.
o HTML
o CSS
o JavaScript
o AJAX
o JQuery
next prev
What is PHP
PHP is a open source, interpreted and object-oriented scripting language i.e. executed at
server side. It is used to develop web applications (an application i.e. executed at server
side and generates dynamic page).
What is PHP
o PHP is a server side scripting language.
PHP Features
There are given many features of PHP.
o Performance: Script written in PHP executes much faster then 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
developed 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:
o XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other
components too such as FileZilla, OpenSSL, Webalizer, OpenSSL, Mercury Mail etc.
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 Example
It is very easy to create a simple PHP example. To do so, create a file and write HTML tags +
PHP code and save this file with .php extension.
All PHP code goes between php tag. A syntax of PHP tag is given below:
1. <?php
2. //your code here
3. ?>
Let's see a simple PHP example where we are writing some text using PHP echo command.
File: first.php
1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
5. echo "<h2>Hello First PHP</h2>";
6. ?>
7. </body>
8. </html>
Output:
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.
Output:
Hello by PHP echo
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.
Output:
Output:
Hello by PHP print this is multi line text printed by PHP print statement
Output:
Output:
PHP Variables
A variable in PHP is a name of memory location that holds data. A variable is a temporary
storage that is used to store data temporarily.
1. $variablename=value;
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:
Output:
11
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. ?>
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
File: variablevalid.php
1. <?php
2. $a="hello";//letter (valid)
3. $_b="hello";//underscore (valid)
4.
5. echo "$a <br/> $_b";
6. ?>
Output:
hello
hello
File: variableinvalid.php
1. <?php
2. $4c="hello";//number (invalid)
3. $*d="hello";//special symbol (invalid)
4.
5. echo "$4c <br/> $*d";
6. ?>
Output:
The $$var (double dollar) is a reference variable that stores the value of the $variable
inside it.
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. ?>
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.
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:
Output:
Output:
File: constant4.php
1. <?php
2. const MESSAGE="Hello const by JavaTpoint PHP";
3. echo MESSAGE;
4. ?>
Output:
Magic Constants
Magic constants are the predefined constants in PHP which get changed on the basis of their
use. They start with double underscore (__) and ends with double underscore.
They are similar to other predefined constants but as they change their values with the
context, they are called magic constants.
There are 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, na
returned.
__DIR__ Represents full directory path of the file. Equivalent to dirname(__file__). It doe
slash unless it is a root directory. It also resolves symbolic link.
__FUNCTION__ Represents the function name where it is used. If it is used outside of any functio
blank.
__CLASS__ Represents the function name where it is used. If it is used outside of any functio
blank.
__TRAIT__ Represents the trait name where it is used. If it is used outside of any function, the
It includes namespace it was declared in.
__METHOD__ Represents the name of the class method where it is used. The method name
declared.
Example
Let's see an example for each of the above magical constants.
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;
78. ?>
Output:
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
2. Compound Types
3. Special Types
1. boolean
2. integer
3. float
4. string
1. array
2. object
1. resource
2. NULL
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 Assignment Operators
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
[ array() left
** arithmetic right
| bitwise OR left
|| logical OR left
?: ternary left
or logical 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.
1. <?php
2. // this is C++ style single line comment
3. # this is Unix Shell style single line comment
4. echo "Welcome to PHP single line comments";
5. ?>
Output:
1. <?php
2. /*
3. Anything placed
4. within comment
5. will not be displayed
6. on the browser;
7. */
8. echo "Welcome to PHP multi line comment";
9. ?>
Output:
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. }
Flowchart
Example
1. <?php
2. $num=12;
3. if($num<100){
4. echo "$num is less than 100";
5. }
6. ?>
Output:
Syntax
1. if(condition){
2. //code to be executed if true
3. }else{
4. //code to be executed if false
5. }
Flowchart
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. ?>
Output:
12 is even number
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
Syntax
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
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
Syntax
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. foreach( $season as $arr ){
4. echo "Season is: $arr<br />";
5. }
6. ?>
Output:
Syntax
1. while(condition){
2. //code to be executed
3. }
Alternative Syntax
1. while(condition):
2. //code to be executed
3.
4. 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
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);
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
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;
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.
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
Output:
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
1. <?php
2. $num=200;
3. switch($num){
4. case 100:
5. echo("number is equals to 100");
6. break;
7. case 200:
8. echo("number is equal to 200");
9. break;
10. case 50:
11. echo("number is equal to 300");
12. break;
13. default:
14. echo("number is not equal to 100, 200 or 500");
15. }
16. ?>
Output:
PHP Programs
PHP programs are frequently asked in the interview. These programs can be asked from
basics, control statements, array, string, oops, file handling etc. Let's see the list of top PHP
programs.
1) Sum of Digits
Write a PHP program to print sum of digits.
Input: 23
Output: 5
Input: 624
Output: 12
Input: 12
3) Prime number
Write a PHP program to check prime number.
Input: 17
4) Table of number
Write a PHP program to print table of a 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
Write a PHP program to print factorial of a number.
Input: 5
Output: 120
Input: 6
Output: 720
6) Armstrong number
Write a PHP program to check armstrong number.
Input: 371
Output: armstrong
Input: 342
Input: 121
Input: 113
8) Fibonacci Series
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
Write a PHP program to reverse given number.
Input: 234
Output: 432
Input: amit
Output: tima
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
Input: 2000
Input: 2001
Output:
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
Output:
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
Output:
enter the range= 6
1
121
12321
1234321
123454321
12345654321
Output:
Output:
Output:
Output:
Output:
Sum of Digits
To find sum of digits of a number just add all the digits.
For example,
1. 14597 = 1 + 4 + 5 + 9 + 7
2. 14597 = 26
Logic:
Example:
1. <?php
2. $num = 14597;
3. $sum=0; $rem=0;
4. for ($i =0; $i<=strlen($num);$i++)
5. {
6. $rem=$num%10;
7. $sum = $sum + $rem;
8. $num=$num/10;
9. }
10. echo "Sum of digits 14597 is $sum";
11. ?>
Output:
Odd numbers are those which are not divisible by 2. Numbers Like 1, 3, 5, 7, 9, 11, etc are
odd.
Logic:
o Take a number.
o Divide it by 2.
Example:
1. <?php
2. $number=1233456;
3. if($number%2==0)
4. {
5. echo "$number is Even Number";
6. }
7. else
8. {
9. echo "$number is Odd Number";
10. }
11. ?>
Output:
Even Odd Program using Form in PHP
By inserting value in a form we can check that inserted value is even or odd.
Example:
1. <html>
2. <body>
3. <form method="post">
4. Enter a number:
5. <input type="number" name="number">
6. <input type="submit" value="Submit">
7. </form>
8. </body>
9. </html>
10. <?php
11. if($_POST){
12. $number = $_POST['number'];
13. //divide entered number by 2
14. //if the reminder is 0 then the number is even otherwise the number is odd
15. if(($number % 2) == 0){
16. echo "$number is an Even number";
17. }else{
18. echo "$number is Odd number";
19. }
20. }
21. ?>
Output:
Prime Number
A number which is only divisible by 1 and itself is called prime number. Numbers 2, 3, 5, 7,
11, 13, 17, etc. are prime numbers.
o It is a natural number greater than 1 and so 0 and 1 are not prime numbers.
Prime number in PHP
Example:
1. <?php
2. $count = 0;
3. $num = 2;
4. while ($count < 15 )
5. {
6. $div_count=0;
7. for ( $i=1; $i<=$num; $i++)
8. {
9. if (($num%$i)==0)
10. {
11. $div_count++;
12. }
13. }
14. if ($div_count<3)
15. {
16. echo $num." , ";
17. $count=$count+1;
18. }
19. $num=$num+1;
20. }
21. ?>
Output:
Prime Number using Form in PHP
Example:
We'll show a form, which will check whether a number is prime or not.
1. <form method="post">
2. Enter a Number: <input type="text" name="input"><br><br>
3. <input type="submit" name="submit" value="Submit">
4. </form>
5. <?php
6. if($_POST)
7. {
8. $input=$_POST['input'];
9. for ($i = 2; $i <= $input-1; $i++) {
10. if ($input % $i == 0) {
11. $value= True;
12. }
13. }
14. if (isset($value) && $value) {
15. echo 'The Number '. $input . ' is not prime';
16. } else {
17. echo 'The Number '. $input . ' is prime';
18. }
19. }
20. ?>
Output:
On entering number 12, we get the following output. It states that 12 is not a prime number.
On entering number 97, we get the following output. It states that 97 is a prime number.
Logic:
Example:
1. <?php
2. define('a', 7);
3. for($i=1; $i<=10; $i++)
4. {
5. echo $i*a;
6. echo '<br>';
7. }
8. ?>
Output:
Factorial Program
The factorial of a number n is defined by the product of all the digits from 1 to n (including 1
and n).
For example,
1. 4! = 4*3*2*1 = 24
2. 6! = 6*5*4*3*2*1 = 720
Note:
o Factorial of 0 is always 1.
o Using loop
Logic:
o Take a number.
o Take the descending positive integers.
o Multiply them.
Factorial in PHP
Factorial of 4 using for loop is shown below.
Example:
1. <?php
2. $num = 4;
3. $factorial = 1;
4. for ($x=$num; $x>=1; $x--)
5. {
6. $factorial = $factorial * $x;
7. }
8. echo "Factorial of $num is $factorial";
9. ?>
Output:
Example:
1. <html>
2. <head>
3. <title>Factorial Program using loop in PHP</title>
4. </head>
5. <body>
6. <form method="post">
7. Enter the Number:<br>
8. <input type="number" name="number" id="number">
9. <input type="submit" name="submit" value="Submit" />
10. </form>
11. <?php
12. if($_POST){
13. $fact = 1;
14. //getting value from input text box 'number'
15. $number = $_POST['number'];
16. echo "Factorial of $number:<br><br>";
17. //start loop
18. for ($i = 1; $i <= $number; $i++){
19. $fact = $fact * $i;
20. }
21. echo $fact . "<br>";
22. }
23. ?>
24. </body>
25. </html>
Output:
Factorial using Recursion in PHP
Factorial of 6 using recursion method is shown.
Example:
1. <?php
2. function fact ($n)
3. {
4. if($n <= 1)
5. {
6. return 1;
7. }
8. else
9. {
10. return $n * fact($n - 1);
11. }
12. }
13.
14. echo "Factorial of 6 is " .fact(6);
15. ?>
Output:
Armstrong Number
An Armstrong number is the one whose value is equal to the sum of the cubes of its digits.
For example,
o Store it in a variable.
Example:
1. <?php
2. $num=407;
3. $total=0;
4. $x=$num;
5. while($x!=0)
6. {
7. $rem=$x%10;
8. $total=$total+$rem*$rem*$rem;
9. $x=$x/10;
10. }
11. if($num==$total)
12. {
13. echo "Yes it is an Armstrong number";
14. }
15. else
16. {
17. echo "No it is not an armstrong number";
18. }
19. ?>
Output:
Look at the above snapshot, the output displays that 407 is an Armstrong number.
Example:
1. <html>
2. <body>
3. <form method="post">
4. Enter the Number:
5. <input type="number" name="number">
6. <input type="submit" value="Submit">
7. </form>
8. </body>
9. </html>
10. <?php
11. if($_POST)
12. {
13. //get the number entered
14. $number = $_POST['number'];
15. //store entered number in a variable
16. $a = $number;
17. $sum = 0;
18. //run loop till the quotient is 0
19. while( $a != 0 )
20. {
21. $rem = $a % 10; //find reminder
22. $sum = $sum + ( $rem * $rem * $rem ); //cube the reminder and add it to the sum var
iable till the loop ends
23. $a = $a / 10; //find quotient. if 0 then loop again
24. }
25. //if the entered number and $sum value matches then it is an armstrong number
26. if( $number == $sum )
27. {
28. echo "Yes $number an Armstrong Number";
29. }else
30. {
31. echo "$number is not an Armstrong Number";
32. }
33. }
34. ?>
Output:
For example, number 24142 is a palindrome number. On reversing it we?ll get the same
number.
Logic:
o Take a number.
1. <?php
2. function palindrome($n){
3. $number = $n;
4. $sum = 0;
5. while(floor($number)) {
6. $rem = $number % 10;
7. $sum = $sum * 10 + $rem;
8. $number = $number/10;
9. }
10. return $sum;
11. }
12. $input = 1235321;
13. $num = palindrome($input);
14. if($input==$num){
15. echo "$input is a Palindrome number";
16. } else {
17. echo "$input is not a Palindrome";
18. }
19. ?>
Output:
1. <form method="post">
2. Enter a Number: <input type="text" name="num"/><br>
3. <button type="submit">Check</button>
4. </form>
5. <?php
6. if($_POST)
7. {
8. //get the value from form
9. $num = $_POST['num'];
10. //reversing the number
11. $reverse = strrev($num);
12.
13. //checking if the number and reverse is equal
14. if($num == $reverse){
15. echo "The number $num is Palindrome";
16. }else{
17. echo "The number $num is not a Palindrome";
18. }
19. }
20. ?>
Output:
Fibonacci
Series
Fibonacci series is the one in which you will get your next term by adding previous two
numbers.
For example,
1. 0 1 1 2 3 5 8 13 21 34
2. Here, 0 + 1 = 1
3. 1+1=2
4. 3+2=5
and so on.
Logic:
o Initializing first and second number as 0 and 1.
o From next number, start your loop. So third number will be the sum of the first two
numbers.
Example:
1. <?php
2. $num = 0;
3. $n1 = 0;
4. $n2 = 1;
5. echo "<h3>Fibonacci series for first 12 numbers: </h3>";
6. echo "\n";
7. echo $n1.' '.$n2.' ';
8. while ($num < 10 )
9. {
10. $n3 = $n2 + $n1;
11. echo $n3.' ';
12. $n1 = $n2;
13. $n2 = $n3;
14. $num = $num + 1;
15. ?>
Output:
Fibonacci series using Recursive function
Recursion is a phenomenon in which the recursion function calls itself until the base condition
is reached.
1. <?php
2. /* Print fiboancci series upto 12 elements. */
3. $num = 12;
4. echo "<h3>Fibonacci series using recursive function:</h3>";
5. echo "\n";
6. /* Recursive function for fibonacci series. */
7. function series($num){
8. if($num == 0){
9. return 0;
10. }else if( $num == 1){
11. return 1;
12. } else {
13. return (series($num-1) + series($num-2));
14. }
15. }
16. /* Call Function. */
17. for ($i = 0; $i < $num; $i++){
18. echo series($i);
19. echo "\n";
20. }
Output:
Reverse number
A number can be written in reverse order.
For example
12345 = 54321
Logic:
o Multiply the reverse number by 10, add the remainder which comes after dividing the
number by 10.
1. <?php
2. $num = 23456;
3. $revnum = 0;
4. while ($num > 1)
5. {
6. $rem = $num % 10;
7. $revnum = ($revnum * 10) + $rem;
8. $num = ($num / 10);
9. }
10. echo "Reverse number of 23456 is: $revnum";
11. ?>
Output:
1. <?php
2. function reverse($number)
3. {
4. /* writes number into string. */
5. $num = (string) $number;
6. /* Reverse the string. */
7. $revstr = strrev($num);
8. /* writes string into int. */
9. $reverse = (int) $revstr;
10. return $reverse;
11. }
12. echo reverse(23456);
13. ?>
Output:/strong>
Reverse String
A string can be reversed either using strrev() function or simple PHP code.
Logic:
Example:
1. <?php
2. $string = "JAVATPOINT";
3. echo "Reverse string of $string is " .strrev ( $string );
4. ?>
Output:
Reverse String Without using strrev() function
A reverse string program without using strrev() function is shown.
Example:
1. <?php
2. $string = "JAVATPOINT";
3. $length = strlen($string);
4. for ($i=($length-1) ; $i >= 0 ; $i--)
5. {
6. echo $string[$i];
7. }
8. ?>
Output:
For example
1. a = 20, b = 30
2. After swapping,
3. a = 30, b = 20
Example:
1. <?php
2. $a = 45;
3. $b = 78;
4. // Swapping Logic
5. $third = $a;
6. $a = $b;
7. $b = $third;
8. echo "After swapping:<br><br>";
9. echo "a =".$a." b=".$b;
10. ?>
Output:
1. <?php
2. $a=234;
3. $b=345;
4. //using arithmetic operation
5. $a=$a+$b;
6. $b=$a-$b;
7. $a=$a-$b;
8. echo "Value of a: $a</br>";
9. echo "Value of b: $b</br>";
10. ?>
Output:
1. <?php
2. $a=234;
3. $b=345;
4. // using arithmetic operation
5. $a=$a*$b;
6. $b=$a/$b;
7. $a=$a/$b;
8. echo "Value of a: $a</br>";
9. echo "Value of b: $b</br>";
10. ?>
Output:
Example:
1. <?php
2. $x=15;
3. $y=30;
4. $z=$x+$y;
5. echo "Sum: ",$z;
6. ?>
Output:
Adding in Form
Two numbers can be added by passing input value in the form.
Example:
1. <html>
2. <body>
3. <form method="post">
4. Enter First Number:
5. <input type="number" name="number1" /><br><br>
6. Enter Second Number:
7. <input type="number" name="number2" /><br><br>
8. <input type="submit" name="submit" value="Add">
9. </form>
10. <?php
11. if(isset($_POST['submit']))
12. {
13. $number1 = $_POST['number1'];
14. $number2 = $_POST['number2'];
15. $sum = $number1+$number2;
16. echo "The sum of $number1 and $number2 is: ".$sum;
17. }
18. ?>
19. </body>
20. </html>
Output:
Adding in Simple Code
Two numbers can be added by passing input value in the form but without using (+) operator.
1. <body>
2. <form>
3. Enter First Number:
4. <input type="number" name="number1" /><br><br>
5. Enter Second Number:
6. <input type="number" name="number2" /><br><br>
7. <input type="submit" name="submit" value="Add">
8. </form>
9. </body>
10. <?php
11. @$number1=$_GET['number1'];
12. @$number2=$_GET['number2'];
13. for ($i=1; $i<=$number2; $i++)
14. {
15. $number1++;
16. }
17. echo "Sum of $number1 and $number2 is=".$number2;
18. ?>
Output:
Example:
1. <?php
2. $x=30;
3. $y=15;
4. $z=$x-$y;
5. echo "Difference: ",$z;
6. ?>
Output:
Subtraction in Form
By inserting values in the form two numbers can be subtracted.
Example:
1. <html>
2. <body>
3. <form method="post">
4. Enter First Number:
5. <input type="number" name="number1" /><br><br>
6. Enter Second Number:
7. <input type="number" name="number2" /><br><br>
8. <input type="submit" name="submit" value="Subtract">
9. </form>
10. <?php
11. if(isset($_POST['submit']))
12. {
13. $number1 = $_POST['number1'];
14. $number2 = $_POST['number2'];
15. $sum = $number1-$number2;
16. echo "The difference of $number1 and $number2 is: ".$sum;
17. }
18. ?>
19. </body>
20. </html>
Output:
Subtraction in Form without (-) Operator
By inserting values in the form two numbers can be subtracted but without using (-) operator.
Example:
1. <body>
2. <form>
3. Enter First Number:
4. <input type="number" name="number1" /><br><br>
5. Enter Second Number:
6. <input type="number" name="number2" /><br><br>
7. <input type="submit" name="submit" value="Subtract">
8. </form>
9. </body>
10. <?php
11.
12. @$number1=$_GET['number1'];
13. @$number2=$_GET['number2'];
14. for ($i=1; $i<=$number2; $i++)
15. {
16. $number1--;
17. }
18. echo "Difference=".$number1;
19. ?>
Output:
Area of Triangle
Area of a triangle is calculated by the following Mathematical formula,
Example:
1. <?php
2. $base = 10;
3. $height = 15;
4. echo "area with base $base and height $height= " . ($base * $height) / 2;
5. ?>
Output:
Example:
1. <html>
2. <body>
3. <form method = "post">
4. Base: <input type="number" name="base">
5. <br><br>
6. Height: <input type="number" name="height"><br>
7. <input type = "submit" name = "submit" value="Calculate">
8. </form>
9. </body>
10. </html>
11. <?php
12. if(isset($_POST['submit']))
13. {
14. $base = $_POST['base'];
15. $height = $_POST['height'];
16. $area = ($base*$height) / 2;
17. echo "The area of a triangle with base as $base and height as $height is $area";
18. }
19. ?>
Output:
Area of a Rectangle
Area of a rectangle is calculated by the mathematical formula,
Logic:
Example:
1. <?php
2. $length = 14;
3. $width = 12;
4. echo "area of rectangle is $length * $width= " . ($length * $width) . "<br />";
5. ?>
Output:
Example:
1. <html>
2. <body>
3. <form method = "post">
4. Width: <input type="number" name="width">
5. <br><br>
6. Length: <input type="number" name="length"> <br>
7. <input type = "submit" name = "submit" value="Calculate">
8. </form>
9. </body>
10. </html>
11. <?php
12. if(isset($_POST['submit']))
13. {
14. $width = $_POST['width'];
15. $length = $_POST['length'];
16. $area = $width*$length;
17. echo "The area of a rectangle with $width x $length is $area";
18. }
19. ?>
Output:
Leap Year
Program
A leap year is the one which has 366 days in a year. A leap year comes after every four years.
Hence a leap year is always a multiple of four.
Example:
1. <?php
2. function isLeap($year)
3. {
4. return (date('L', mktime(0, 0, 0, 1, 1, $year))==1);
5. }
6. //For testing
7. for($year=1991; $year<2016; $year++)
8. {
9. If (isLeap($year))
10. {
11. echo "$year : LEAP YEAR<br />\n";
12. }
13. else
14. {
15. echo "$year : Not leap year<br />\n";
16. }
17. }
18. ?>
Output:
Leap Year Program in Form
This program states whether a year is leap year or not by inserting a year in the form.
Example:
1. <html>
2. <body>
3. <form method="post">
4. Enter the Year: <input type="text" name="year">
5. <input type="submit" name="submit" value="Submit">
6. </form>
7. </body>
8. </html>
9. <?php
10. if($_POST)
11. {
12. //get the year
13. $year = $_POST['year'];
14. //check if entered value is a number
15. if(!is_numeric($year))
16. {
17. echo "Strings not allowed, Input should be a number";
18. return;
19. }
20. //multiple conditions to check the leap year
21. if( (0 == $year % 4) and (0 != $year % 100) or (0 == $year % 400) )
22. {
23. echo "$year is a Leap Year";
24. }
25. else
26. {
27. echo "$year is not a Leap Year";
28. }
29. }
30. ?>
Output:
Alphabet
Triangle Method
There are three methods to print the alphabets in a triangle or in a pyramid form.
Logic:
Example:
1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=5; $j>$i; $j--){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>
Output:
Example:
1. <?php
2. for( $i=65; $i<=69; $i++){
3. for($j=5; $j>=$i-64; $j--){
4. echo chr($i);
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Using range() function with foreach
In this methods we use foreach loop with range() function. The range() function contain values
in an array and returns it with $char variable. The for loop is used to print the output.
Example:
1. <?php
2. $k=1;
3. foreach(range('A','Z') as $char){
4. for($i=5; $i>=$k; $i--){
5. echo $char;
6. }
7. echo "<br>";
8. $k=$k+1;
Output:
Pattern 1
1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=5; $j>$i; $j--){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>
Output:
Pattern 2
1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=0; $j<=$i; $j++){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>
Output:
Pattern 3
1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=0; $j<=$i; $j++){
5. echo $alpha[$j];
6. }
7. echo "<br>";
8. }
9. ?>
Output:
Pattern 4
1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=4; $j>=$i; $j--){
5. echo $alpha[$j];
6. }
7. echo "<br>";
8. }
9. ?>
Output:
Pattern 5
1. <?php
2. $alpha = range('A', 'Z');
3. for ($i=5; $i>=1; $i--) {
4. for($j=0; $j<=$i; $j++) {
5. echo '';
6. }
7. $j--;
8. for ($k=0; $k<=(5-$j); $k++) {
9. echo $alpha[$k];
10. }
11. echo "<br>\n";
12. }
13. ?>
Output:
Number Triangle
Number triangle in PHP can be printed using for and foreach loop. There are a lot of patterns
in number triangle. Some of them are show here.
Pattern1
1. <?php
2. $k=1;
3. for($i=0;$i<4;$i++){
4. for($j=0;$j<=$i;$j++){
5. echo $k." ";
6. $k++;
7. }
8. echo "<br>";
9. }
10. ?>
Output:
Pattern 2
1. <?php
2. $k=1;
3. for($i=0;$i<5;$i++){
4. for($j=0;$j<=$i;$j++){
5. if($j%2==0)
6. {
7. $k=0;
8. }
9. else
10. {
11. $k=1;
12. }
13. echo $k." ";
14. }
15. echo "<br>";
16. }
17. ?>
Output:
Pattern 3
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo $j;
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Pattern 4
1. <?php
2. for($i=0;$i>=5;$i++){
3. for($j=1;$j>=$i;$j++){
4. echo $i;
5. }
6. echo "<br>";
7. }
8. ?<
Output:
Pattern 5
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo "1";
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Pattern 6
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo "1";
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Pattern 7
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo $j;
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Pattern 8
1. <?php
2. for($i=5;$i>=1;$i--){
3. for($j=$i;$j>=1;$j--){
4. echo $i."";
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Star Triangle
The star triangle in PHP is made using for and foreach loop. There are a lot of star patterns.
We'll show some of them here.
Pattern 1
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo "* ";
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Pattern 2
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo "* ";
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Pattern 3
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($k=5;$k>=$i;$k--){
4. echo " ";
5. }
6. for($j=1;$j<=$i;$j++){
7. echo "* ";
8. }
9. echo "<br>";
10. }
11. for($i=4;$i>=1;$i--){
12. for($k=5;$k>=$i;$k--){
13. echo " ";
14. }
15. for($j=1;$j<=$i;$j++){
16. echo "* ";
17. }
18. echo "<br>";
19. }
20. ?>
Output:
Pattern 4
1. <?php
2. for($i=1; $i<=5; $i++){
3. for($j=1; $j<=$i; $j++){
4. echo ' * ';
5. }
6. echo '<br>';
7. }
8. for($i=5; $i>=1; $i--){
9. for($j=1; $j<=$i; $j++){
10. echo ' * ';
11. }
12. echo '<br>';
13. }
14. ?>
Output:
Pattern 5
1. <?php
2. for ($i=1; $i<=5; $i++)
3. {
4. for ($j=1; $j<=5; $j++)
5. {
6. echo '* ';
7. }
8. echo "</br>";
9. }
10. ?>
Output:
Pattern 6
1. <?php
2. for($i=5; $i>=1; $i--)
3. {
4. if($i%2 != 0)
5. {
6. for($j=5; $j>=$i; $j--)
7. {
8. echo "* ";
9. }
10. echo "<br>";
11. }
12. }
13. for($i=2; $i<=5; $i++)
14. {
15. if($i%2 != 0)
16. {
17. for($j=5; $j>=$i; $j--)
18. {
19. echo "* ";
20. }
21. echo "<br>";
22. }
23. }
24. ?>
Output:
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument
list and return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive
function also.
Less Code: It saves a lot of code because you don't need to write the logic many times. By
the use of function, you can write the logic only once and reuse it.
Syntax
1. function functionname(){
2. //code to be executed
3. }
Note: Function name must be start with letter and underscore only like other labels in PHP. It can't be
start with numbers or special symbols.
1. <?php
2. function sayHello(){
3. echo "Hello PHP Function";
4. }
5. sayHello();//calling function
6. ?>
Output:
File: functionarg.php
1. <?php
2. function sayHello($name){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Sonoo");
6. sayHello("Vimal");
7. sayHello("John");
8. ?>
Output:
Hello Sonoo
Hello Vimal
Hello John
File: functionarg2.php
1. <?php
2. function sayHello($name,$age){
3. echo "Hello $name, you are $age years old<br/>";
4. }
5. sayHello("Sonoo",27);
6. sayHello("Vimal",29);
7. sayHello("John",23);
8. ?>
Output:
By default, value passed to the function is call by value. To pass value as a reference, you
need to use ampersand (&) symbol before the argument name.
File: functionref.php
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>
Output:
File: functiondefaultarg.php
1. <?php
2. function sayHello($name="Sonoo"){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Rajesh");
6. sayHello();//passing no value
7. sayHello("John");
8. ?>
Output:
Hello Rajesh
Hello Sonoo
Hello John
File: functiondefaultarg.php
1. <?php
2. function cube($n){
3. return $n*$n*$n;
4. }
5. echo "Cube of 3 is: ".cube(3);
6. ?>
Output:
Cube of 3 is: 27
PHP Parameterized Function
PHP Parameterized functions are the functions with parameters. You can pass any number of
parameters inside a function. These passed parameters act as variables inside your function.
They are specified inside the parentheses, after the function name.
The output depends upon the dynamic values passed as the parameters into the function.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Parameter Addition and Subtraction Example</title>
5. </head>
6. <body>
7. <?php
8. //Adding two numbers
9. function add($x, $y) {
10. $sum = $x + $y;
11. echo "Sum of two numbers is = $sum <br><br>";
12. }
13. add(467, 943);
14.
15. //Subtracting two numbers
16. function sub($x, $y) {
17. $diff = $x - $y;
18. echo "Difference between two numbers is = $diff";
19. }
20. sub(943, 467);
21. ?>
22. </body>
23. </html>
Output:
1. <?php
2. //add() function with two parameter
3. function add($x,$y)
4. {
5. $sum=$x+$y;
6. echo "Sum = $sum <br><br>";
7. }
8. //sub() function with two parameter
9. function sub($x,$y)
10. {
11. $sub=$x-$y;
12. echo "Diff = $sub <br><br>";
13. }
14. //call function, get two argument through input box and click on add or sub button
15. if(isset($_POST['add']))
16. {
17. //call add() function
18. add($_POST['first'],$_POST['second']);
19. }
20. if(isset($_POST['sub']))
21. {
22. //call add() function
23. sub($_POST['first'],$_POST['second']);
24. }
25. ?>
26. <form method="post">
27. Enter first number: <input type="number" name="first"/><br><br>
28. Enter second number: <input type="number" name="second"/><br><br>
29. <input type="submit" name="add" value="ADDITION"/>
30. <input type="submit" name="sub" value="SUBTRACTION"/>
31. </form>
Output:
Example 1
In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Value' string. But, printing $str variable results 'Hello' only. It is because changes are
done in the local variable $str2 only. It doesn't reflect to $str variable.
1. <?php
2. function adder($str2)
3. {
4. $str2 .= 'Call By Value';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>
Output:
Hello
Example 2
Let's understand PHP call by value concept through another example.
1. <?php
2. function increment($i)
3. {
4. $i++;
5. }
6. $i = 10;
7. increment($i);
8. echo $i;
9. ?>
Output:
10
Example 1
In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Reference' string. Here, printing $str variable results 'This is Call By Reference'. It is
because changes are done in the actual variable $str.
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'This is ';
7. adder($str);
8. echo $str;
9. ?>
Output:
1. <?php
2. function increment(&$i)
3. {
4. $i++;
5. }
6. $i = 10;
7. increment($i);
8. echo $i;
9. ?>
Output:
11
Let' see the simple example of using PHP default arguments in function.
Example 1
1. <?php
2. function sayHello($name="Ram"){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Sonoo");
6. sayHello();//passing no value
7. sayHello("Vimal");
8. ?>
Output:
Hello Sonoo
Hello Ram
Hello Vimal
Since PHP 5, you can use the concept of default argument value with call by reference also.
Example 2
1. <?php
2. function greeting($first="Sonoo",$last="Jaiswal"){
3. echo "Greeting: $first $last<br/>";
4. }
5. greeting();
6. greeting("Rahul");
7. greeting("Michael","Clark");
8. ?>
Output:
Output:
Addition is: 20
Addition is: 30
Addition is: 80
The 3 dot concept is implemented for variable length argument since PHP 5.6.
Output:
10
It is recommended to avoid recursive function call over 200 recursion level because it may
smash the stack and may cause the termination of script.
Output:
1
2
3
4
5
Example 2 : Factorial Number
1. <?php
2. function factorial($n)
3. {
4. if ($n < 0)
5. return -1; /*Wrong value*/
6. if ($n == 0)
7. return 1; /*Terminating condition*/
8. return ($n * factorial ($n -1));
9. }
10.
11. echo factorial(5);
12. ?>
Output:
120
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
1st way:
1. $season=array("summer","winter","spring","autumn");
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
1st way:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>
Output:
Output:
PHP indexed array can store numbers, strings or any object. PHP indexed array is also known
as numeric array.
Definition
There are two ways to define indexed array:
1st way:
1. $size=array("Big","Medium","Short");
2nd way:
1. $size[0]="Big";
2. $size[1]="Medium";
3. $size[2]="Short";
Output:
Output:
File: array3.php
1. <?php
2. $size=array("Big","Medium","Short");
3. foreach( $size as $s )
4. {
5. echo "Size is: $s<br />";
6. }
7. ?>
Output:
1. <?php
2. $size=array("Big","Medium","Short");
3. echo count($size);
4. ?>
Output:
3
Definition
There are two ways to define associative array:
1st way:
1. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
2nd way:
1. $salary["Sonoo"]="550000";
2. $salary["Vimal"]="250000";
3. $salary["Ratan"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
5. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
6. ?>
Output:
Output:
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. foreach($salary as $k => $v) {
4. echo "Key: ".$k." Value: ".$v."<br/>";
5. }
6. ?>
Output:
Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );
PHP Multidimensional Array Example
Let's see a simple example of PHP multidimensional array to display following tabular data.
In this example, we are displaying 3 rows and 3 columns.
Id Name Salary
1 sonoo 400000
2 john 500000
3 rahul 300000
File: multiarray.php
1. <?php
2. $emp = array
3. (
4. array(1,"sonoo",400000),
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
11. echo $emp[$row][$col]." ";
12. }
13. echo "<br/>";
14. }
15. ?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]" ;
4. ?>
Output:
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_UPPER));
4. ?>
Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_LOWER));
4. ?>
Output:
Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>
Output:
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>
Output:
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. sort($season);
4. foreach( $season as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
summer
winter
Syntax
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
winter
summer
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>
Output:
Example
1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>
Output:
sonoo
smith
PHP String
A PHP string is a sequence of characters i.e. used to store and manipulate text. There are 4
ways to specify string in PHP.
o single quoted
o double quoted
o heredoc syntax
1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?>
Output:
Hello text within single quote
We can store multiple line text, special characters and escape sequences in a single quoted
PHP string.
1. <?php
2. $str1='Hello text
3. multiple line
4. text within single quoted string';
5. $str2='Using double "quote" directly inside single quoted string';
6. $str3='Using escape sequences \n in single quoted string';
7. echo "$str1 <br/> $str2 <br/> $str3";
8. ?>
Output:
Note: In single quoted PHP strings, most escape sequences and variables will not be interpreted. But,
we can use single quote through \' and backslash through \\ inside single quoted PHP strings.
1. <?php
2. $num1=10;
3. $str1='trying variable $num1';
4. $str2='trying backslash n and backslash t inside single quoted string \n \t';
5. $str3='Using single quote \'my quote\' and \\backslash';
6. echo "$str1 <br/> $str2 <br/> $str3";
7. ?>
Output:
1. <?php
2. $str="Hello text within double quote";
3. echo $str;
4. ?>
Output:
Now, you can't use double quote directly inside double quoted string.
1. <?php
2. $str1="Using double "quote" directly inside double quoted string";
3. echo $str1;
4. ?>
Output:
We can store multiple line text, special characters and escape sequences in a double
quoted PHP string.
1. <?php
2. $str1="Hello text
3. multiple line
4. text within double quoted string";
5. $str2="Using double \"quote\" with backslash inside double quoted string";
6. $str3="Using escape sequences \n in double quoted string";
7. echo "$str1 <br/> $str2 <br/> $str3";
8. ?>
Output:
1. <?php
2. $num1=10;
3. echo "Number is: $num1";
4. ?>
Output:
Number is: 10
Syntax
Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtolower($str);
4. echo $str;
5. ?>
Output:
my name is khan
Syntax
Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtoupper($str);
4. echo $str;
5. ?>
Output:
MY NAME IS KHAN
Syntax
Example
1. <?php
2. $str="my name is KHAN";
3. $str=ucfirst($str);
4. echo $str;
5. ?>
Output:
My name is KHAN
Syntax
Example
1. <?php
2. $str="MY name IS KHAN";
3. $str=lcfirst($str);
4. echo $str;
5. ?>
Output:
mY name IS KHAN
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=ucwords($str);
4. echo $str;
5. ?>
Output:
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strrev($str);
4. echo $str;
5. ?>
Output:
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strlen($str);
4. echo $str;
5. ?>
Output:
24
PHP Math
PHP provides many predefined math constants and functions that can be used to perform
mathematical operations.
Syntax
1. number abs ( mixed $number )
Example
1. <?php
2. echo (abs(-7)."<br/>"); // 7 (integer)
3. echo (abs(7)."<br/>"); //7 (integer)
4. echo (abs(-7.2)."<br/>"); //7.2 (float/double)
5. ?>
Output:
7
7
7.2
PHP Math: ceil() function
The ceil() function rounds fractions up.
Syntax
1. float ceil ( float $value )
Example
1. <?php
2. echo (ceil(3.3)."<br/>");// 4
3. echo (ceil(7.333)."<br/>");// 8
4. echo (ceil(-4.8)."<br/>");// -4
5. ?>
Output:
4
8
-4
Syntax
1. float floor ( float $value )
Example
1. <?php
2. echo (floor(3.3)."<br/>");// 3
3. echo (floor(7.333)."<br/>");// 7
4. echo (floor(-4.8)."<br/>");// -5
5. ?>
Output:
3
7
-5
Syntax
1. float sqrt ( float $arg )
Example
1. <?php
2. echo (sqrt(16)."<br/>");// 4
3. echo (sqrt(25)."<br/>");// 5
4. echo (sqrt(7)."<br/>");// 2.6457513110646
5. ?>
Output:
4
5
2.6457513110646
Syntax
1. string decbin ( int $number )
Example
1. <?php
2. echo (decbin(2)."<br/>");// 10
3. echo (decbin(10)."<br/>");// 1010
4. echo (decbin(22)."<br/>");// 10110
5. ?>
Output:
10
1010
10110
Syntax
1. string dechex ( int $number )
Example
1. <?php
2. echo (dechex(2)."<br/>");// 2
3. echo (dechex(10)."<br/>");// a
4. echo (dechex(22)."<br/>");// 16
5. ?>
Output:
2
a
16
Syntax
1. string decoct ( int $number )
Example
1. <?php
2. echo (decoct(2)."<br/>");// 2
3. echo (decoct(10)."<br/>");// 12
4. echo (decoct(22)."<br/>");// 26
5. ?>
Output:
2
12
26
Syntax
1. string base_convert ( string $number , int $frombase , int $tobase )
Example
1. <?php
2. $n1=10;
3. echo (base_convert($n1,10,2)."<br/>");// 1010
4. ?>
Output:
1010
Syntax
1. number bindec ( string $binary_string )
Example
1. <?php
2. echo (bindec(10)."<br/>");// 2
3. echo (bindec(1010)."<br/>");// 10
4. echo (bindec(1011)."<br/>");// 11
5. ?>
Output:
2
10
11
o abs()
o acos()
o acosh()
o asin()
o asinh()
o atan()
o atan2()
o atanh()
o base_convert()
o bindec()
o ceil()
o cos()
o cosh()
o decbin()
o dechex()
o decoct()
o deg2rad()
o exp()
o expm1()
o floor()
o fmod()
o getrandmax()
o hexdec()
o hypot()
o is_finite()
o is_infinite()
o is_nan()
o lcg_value()
o log()
o log10()
o log1p()
o max()
o min()
o mt_getrandmax()
o mt_rand()
o mt_srand()
o octdec()
o pi()
o pow()
o rad2deg()
o rand()
o round()
o sin()
o sinh()
o sqrt()
o srand()
o tan()
o tanh()
The form request may be get or post. To retrieve data from get request, we need to use
$_GET, for post request $_POST.
Let's see a simple example to receive data from get request in PHP.
File: form1.html
1. <form action="welcome.php" method="get">
2. Name: <input type="text" name="name"/>
3. <input type="submit" value="visit"/>
4. </form>
File: welcome.php
1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variable
3. echo "Welcome, $name";
4. ?>
The data passed through post request is not visible on the URL browser so it is secured. You
can send large amount of data through post request.
Let's see a simple example to receive data from post request in PHP.
File: form1.html
1. <form action="login.php" method="post">
2. <table>
3. <tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
4. <tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>
5. <tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
6. </table>
7. </form>
File: login.php
1. <?php
2. $name=$_POST["name"];//receiving name field value in $name variable
3. $password=$_POST["password"];//receiving password field value in $password variable
4.
5. echo "Welcome: $name, your password is: $password";
6. ?>
Output:
PHP
Include File
PHP allows you to include file so that a page content can be reused many times. There are
two ways to include file in PHP.
1. include
2. require
Advantage
Code Reusability: By the help of include and require construct, we can reuse HTML code or
PHP script in many PHP scripts.
Output:
File: menu.html
1. <a href="http://www.javatpoint.com">Home</a> |
2. <a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
3. <a href="http://www.javatpoint.com/java-tutorial">Java</a> |
4. <a href="http://www.javatpoint.com/html-tutorial">HTML</a>
File: require1.php
1. <?php require("menu.html"); ?>
2. <h1>This is Main Page</h1>
Output:
PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user.
Cookie is created at server side and saved to client browser. Each time when client sends
request to the server, cookie is embedded with request. Such way, cookie can be received at
the server side.
Syntax
1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Example
PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.
Example
1. $value=$_COOKIE["CookieName"];//returns cookie value
1. <?php
2. setcookie("user", "Sonoo");
3. ?>
4. <html>
5. <body>
6. <?php
7. if(!isset($_COOKIE["user"])) {
8. echo "Sorry, cookie is not found!";
9. } else {
10. echo "<br/>Cookie Value: " . $_COOKIE["user"];
11. }
12. ?>
13. </body>
14. </html>
Output:
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
File: cookie1.php
1. <?php
2. setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
3. ?>
PHP Session
PHP session is used to store and pass information from one page to another temporarily (until
user close the website).
PHP session technique is widely used in shopping websites where we need to store and pass
cart information e.g. username, product code, product name, product price etc from one page
to another.
PHP session creates unique user id for each browser to recognize the user and avoid conflict
between multiple browsers.
Syntax
Example
1. session_start();
PHP $_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to set
and get session variable values.
1. echo $_SESSION["user"];
File: session3.php
1. <?php
2. session_start();
3. session_destroy();
4. ?>
Syntax
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resour
ce $context ]] )
Example
1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>
Click me for more details...
PHP Close File - fclose()
The PHP fclose() function is used to close an open file pointer.
Syntax
Example
1. <?php
2. fclose($handle);
3. ?>
Syntax
Example
1. <?php
2. $filename = "c:\\myfile.txt";
3. $handle = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($handle, filesize($filename));//read file
6.
7. echo $contents;//printing data of file
8. fclose($handle);//close file
9. ?>
Output
Syntax
Example
1. <?php
2. $fp = fopen('data.txt', 'w');//open file in write mode
3. fwrite($fp, 'hello ');
4. fwrite($fp, 'php file');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>
Output
Syntax
Example
1. <?php
2. unlink('data.txt');
3.
4. echo "File deleted successfully";
5. ?>
Syntax
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resour
ce $context ]] )
r Opens file in read-only mode. It places the file pointer at the beginning of the file.
r+ Opens file in read-write mode. It places the file pointer at the beginning of the file.
w Opens file in write-only mode. It places the file pointer to the beginning of the file and trun
length. If file is not found, it creates a new file.
w+ Opens file in read-write mode. It places the file pointer to the beginning of the file and trun
length. If file is not found, it creates a new file.
a Opens file in write-only mode. It places the file pointer to the end of the file. If file is not found
a+ Opens file in read-write mode. It places the file pointer to the end of the file. If file is not found
x Creates and opens file in write-only mode. It places the file pointer at the beginning of the file. I
function returns FALSE.
c Opens file in write-only mode. If the file does not exist, it is created. If it exists, it is neither tr
to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on
file
o fread()
o fgets()
o fgetc()
Syntax
Example
1. <?php
2. $filename = "c:\\file1.txt";
3. $fp = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($fp, filesize($filename));//read file
6.
7. echo "<pre>$contents</pre>";//printing data of file
8. fclose($fp);//close file
9. ?>
Output
Syntax
Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. echo fgets($fp);
4. fclose($fp);
5. ?>
Output
Syntax
Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. while(!feof($fp)) {
4. echo fgetc($fp);
5. }
6. fclose($fp);
7. ?>
Output
Syntax
Example
1. <?php
2. $fp = fopen('data.txt', 'w');//opens file in write-only mode
3. fwrite($fp, 'welcome ');
4. fwrite($fp, 'to php file write');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>
Output: data.txt
1. <?php
2. $fp = fopen('data.txt', 'w');//opens file in write-only mode
3. fwrite($fp, 'hello');
4. fclose($fp);
5.
6. echo "File written successfully";
7. ?>
Output: data.txt
hello
PHP Append to File
If you use a mode, it will not erase the data of the file. It will write the data at the end of the
file. Visit the next page to see the example of appending data into file.
data.txt
Example
1. <?php
2. $fp = fopen('data.txt', 'a');//opens file in append mode
3. fwrite($fp, ' this is additional text ');
4. fwrite($fp, 'appending data');
5. fclose($fp);
6.
7. echo "File appended successfully";
8. ?>
Output: data.txt
PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is
deleted successfully otherwise FALSE.
Syntax
1. bool unlink ( string $filename [, resource $context ] )
Output
PHP file upload features allows you to upload binary and text files both. Moreover, you can
have the full control over the file to be uploaded through PHP authentication and file operation
functions.
PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we
can get file name, file type, file size, temp file name and errors associated with file.
$_FILES['filename']['name']
returns file name.
$_FILES['filename']['type']
returns MIME type of the file.
$_FILES['filename']['size']
returns size of the file (in bytes).
$_FILES['filename']['tmp_name']
returns temporary file name of the file which was stored on the server.
$_FILES['filename']['error']
returns error code associated with this file.
move_uploaded_file() function
The move_uploaded_file() function moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded thorough the POST
request. It moves the file if it is uploaded through the POST request.
Syntax
1. <?php
2. $target_path = "e:/";
3. $target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
4.
5. if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
6. echo "File uploaded successfully!";
7. } else{
8. echo "Sorry, file not uploaded, please try again!";
9. }
10. ?>
$use_include_path: it is the optional parameter. It is by default false. You can set it to true
to the search the file in the included_path.
PHP Mail
PHP mail() function is used to send email in PHP. You can send text message, html message
and attachment with message using PHP mail() function.
1. bool mail ( string $to , string $subject , string $message [, string $additional_headers [, stri
ng $additional_parameters ]] )
$to: specifies receiver or receivers of the mail. The receiver must be specified one of the
following forms.
o [email protected], [email protected]
o User <[email protected]>
Note: Each line of the message should be separated with a CRLF ( \r\n ) and lines should not be larger
than 70 characters.
$additional_headers (optional): specifies the additional headers such as From, CC, BCC
etc. Extra additional headers should also be separated with CRLF ( \r\n ).
1. <?php
2. ini_set("sendmail_from", "[email protected]");
3. $to = "[email protected]";//change receiver address
4. $subject = "This is subject";
5. $message = "This is simple text message.";
6. $header = "From:[email protected] \r\n";
7.
8. $result = mail ($to,$subject,$message,$header);
9.
10. if( $result == true ){
11. echo "Message sent successfully...";
12. }else{
13. echo "Sorry, unable to send mail...";
14. }
15. ?>
If you run this code on the live server, it will send an email to the specified receiver.
1. <?php
2. $to = "[email protected]";//change receiver address
3. $subject = "This is subject";
4. $message = "<h1>This is HTML heading</h1>";
5.
6. $header = "From:[email protected] \r\n";
7. $header .= "MIME-Version: 1.0 \r\n";
8. $header .= "Content-type: text/html;charset=UTF-8 \r\n";
9.
10. $result = mail ($to,$subject,$message,$header);
11.
12. if( $result == true ){
13. echo "Message sent successfully...";
14. }else{
15. echo "Sorry, unable to send mail...";
16. }
17. ?>
1. <?php
2. $to = "[email protected]";
3. $subject = "This is subject";
4. $message = "This is a text message.";
5. # Open a file
6. $file = fopen("/tmp/test.txt", "r" );//change your file location
7. if( $file == false )
8. {
9. echo "Error in opening file";
10. exit();
11. }
12. # Read the file into a variable
13. $size = filesize("/tmp/test.txt");
14. $content = fread( $file, $size);
15.
16. # encode the data for safe transit
17. # and insert \r\n after every 76 chars.
18. $encoded_content = chunk_split( base64_encode($content));
19.
20. # Get a random 32 bit number using time() as seed.
21. $num = md5( time() );
22.
23. # Define the main headers.
24. $header = "From:[email protected]\r\n";
25. $header .= "MIME-Version: 1.0\r\n";
26. $header .= "Content-Type: multipart/mixed; ";
27. $header .= "boundary=$num\r\n";
28. $header .= "--$num\r\n";
29.
30. # Define the message section
31. $header .= "Content-Type: text/plain\r\n";
32. $header .= "Content-Transfer-Encoding:8bit\r\n\n";
33. $header .= "$message\r\n";
34. $header .= "--$num\r\n";
35.
36. # Define the attachment section
37. $header .= "Content-Type: multipart/mixed; ";
38. $header .= "name=\"test.txt\"\r\n";
39. $header .= "Content-Transfer-Encoding:base64\r\n";
40. $header .= "Content-Disposition:attachment; ";
41. $header .= "filename=\"test.txt\"\r\n\n";
42. $header .= "$encoded_content\r\n";
43. $header .= "--$num--";
44.
45. # Send email now
46. $result = mail ( $to, $subject, "", $header );
47. if( $result == true ){
48. echo "Message sent successfully...";
49. }else{
50. echo "Sorry, unable to send mail...";
51. }
52. ?>
o mysqli_connect()
o PDO::__construct()
PHP mysqli_connect()
PHP mysqli_connect() function is used to connect with MySQL database. It
returns resource if connection is established or null.
Syntax
1. resource mysqli_connect (server, username, password)
PHP mysqli_close()
PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if
connection is closed or false.
Syntax
1. bool mysqli_close(resource $resource_link)
Output:
Connected successfully
o mysqli_query()
o PDO::__query()
PHP MySQLi Create Database Example
Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $conn = mysqli_connect($host, $user, $pass);
6. if(! $conn )
7. {
8. die('Could not connect: ' . mysqli_connect_error());
9. }
10. echo 'Connected successfully<br/>';
11.
12. $sql = 'CREATE Database mydb';
13. if(mysqli_query( $conn,$sql)){
14. echo "Database mydb created successfully.";
15. }else{
16. echo "Sorry, database creation failed ".mysqli_error($conn);
17. }
18. mysqli_close($conn);
19. ?>
Output:
Connected successfully
Database mydb created successfully.
o mysqli_query()
o PDO::__query()
Output:
Connected successfully
Table emp5 created successfully
o mysqli_query()
o PDO::__query()
Output:
Connected successfully
Record inserted successfully
o mysqli_query()
o PDO::__query()
Output:
Connected successfully
Record updated successfully
o mysqli_query()
o PDO::__query()
Output:
Connected successfully
Record deleted successfully
o mysqli_query()
o PDO::__query()
Output:
Connected successfully
EMP ID :1
EMP NAME : ratan
EMP SALARY : 9000
--------------------------------
EMP ID :2
EMP NAME : karan
EMP SALARY : 40000
--------------------------------
EMP ID :3
EMP NAME : jai
EMP SALARY : 90000
--------------------------------
o mysqli_query()
o PDO::__query()
The order by clause is used to fetch data in ascending order or descending order on the basis
of column.
Let's see the query to select data from emp4 table in ascending order on the basis of name
column.
Let's see the query to select data from emp4 table in descending order on the basis of name
column.
Output:
Connected successfully
EMP ID :3
EMP NAME : jai
EMP SALARY : 90000
--------------------------------
EMP ID :2
EMP NAME : karan
EMP SALARY : 40000
--------------------------------
EMP ID :1
EMP NAME : ratan
EMP SALARY : 9000
--------------------------------
1) What is PHP?
PHP stands for Hypertext Preprocessor. It is an open source server-side scripting language
which is widely used for web development. It supports many databases like MySQL, Oracle,
Sybase, Solid, PostgreSQL, generic ODBC etc.
More Details...
In dynamic websites, content of script can be changed at the run time. Its content is
regenerated every time a user visit or reload. Google, yahoo and every search engine is the
example of dynamic website.
o Joomla
o Magento
o Drupal etc.
o CodeIgniter
o Yii 2
o Symfony
o Spaceship operator
o Anonymous classes
o Closure::call method
o Generator delegation
Syntax:
Syntax:
Echo is faster than print because it does not return any value.
Syntax:
1. $variableName=value;
More details...
16) What is the difference between $message and
$$message?
$message stores variable data while $$message is used to store variable of variables.
$message stores fixed data whereas the data stored in $$message may be changed
dynamically.
More Details...
More details...
More Details...
o Scalar types
o Compound types
o Special types
More Details...
20) How to do single and multi line comment in PHP?
PHP single line comment is done in two ways:
PHP multi line comment is done by enclosing all lines within /* */.
More details...
More details...
26) Explain PHP variable length argument function
PHP supports variable length argument function. It means you can pass 0, 1 or n number of
arguments in function. To do this, you need to use 3 ellipses (dots) before the argument
name. The 3 dot concept is implemented for variable length argument since PHP 5.6.
More details...
More Details...
o Indexed array
o Associative array
o Multidimensional array
o array()
o array_change_key_case()
o array_chunk()
o count()
o sort()
o array_reverse()
o array_search()
o array_intersect()
More details...
1. $season=array("summer","winter","spring","autumn");
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
More Details...
More Details...
o strtolower()
o strtoupper()
o ucfirst()
o lcfirst()
o ucwords()
o strrev()
o strlen()
More details...
More Details...
1. include
2. require
More details...
More Details...
Syntax:
1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
More details...
Sessions generally store temporary data to allow multiple PHP pages to offer a complete
functional transaction for the same user.
More Details...
More details...
More details...
44) What is the difference between session and cookie?
The main difference between session and cookie is that cookies are stored on user's computer
in the text file format while sessions are stored on the server side.
Cookies can't hold multiple variables on the other hand Session can hold multiple variables.
You can manually set an expiry for a cookie, while session only remains active as long as
browser is open.
Syntax:
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resour
ce $context ]] )
More details...
o fread()
o fgets()
o fgetc()
More details...
More details...
48) How to delete file in PHP?
The unlink() function is used to delete file in PHP.
More Details...
More Details...
More Details...
1. bool mail($to,$subject,$message,$header);
More Details...
More Details...
More Details...
o mysqli_query()
o PDO::_query()
More details...
You can change the script run time by changing the max_execution_time directive in php.ini
file.
When a script is called, set_time_limit function restarts the timeout counter from zero. It
means, if default timer is set to 30 sec, and 20 sec is specified in function set_time_limit(),
then script will run for 45 seconds. If 0sec is specified in this function, script takes unlimited
time.
57) What are the different types of errors in PHP?
There are 3 types of error in PHP.
Notices:These are non-critical errors. These errors are not displayed to the users.
Warnings:These are more serious errors but they do not result in script termination. By
default, these errors are displayed to the user.
Fatal Errors:These are the most critical errors. These errors may cause due to immediate
termination of script.
1) PHP json_encode
The json_encode() function returns the JSON representation of a value. In other words, it
converts PHP variable (containing array) into JSON.
Syntax:
1. <?php
2. $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
3. echo json_encode($arr);
4. ?>
Output
{"a":1,"b":2,"c":3,"d":4,"e":5}
PHP json_encode example 2
Let's see the example to encode JSON.
1. <?php
2. $arr2 = array('firstName' => 'Rahul', 'lastName' => 'Kumar', 'email' => '[email protected]')
;
3. echo json_encode($arr2);
4. ?>
Output
{"firstName":"Rahul","lastName":"Kumar","email":"[email protected]"}
2) PHP json_decode
The json_decode() function decodes the JSON string. In other words, it converts JSON string
into a PHP variable.
Syntax:
1. mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options
= 0 ]]] )
PHP json_decode example 1
Let's see the example to decode JSON string.
1. <?php
2. $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
3. var_dump(json_decode($json, true));//true means returned object will be converted i
nto associative array
4. ?>
Output
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
PHP json_decode example 2
Let's see the example to decode JSON string.
1. <?php
2. $json2 = '{"firstName" : "Rahul", "lastName" : "Kumar", "email" : "[email protected]"}';
3. var_dump(json_decode($json2, true));
4. ?>
Output
array(3) {
["firstName"]=> string(5) "Rahul"
["lastName"]=> string(5) "Kumar"
["email"]=> string(15) "[email protected]"
}