PHP Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 93

PHP Tutorial

PHP tutorial for beginners and professionals provides in-depth 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 an interpreted language, i.e., there is no need for compilation.
o PHP is a server-side scripting language.
o PHP is faster than other scripting languages, for example, ASP and JSP.

PHP Example
In this tutorial, you will get a lot of PHP examples to understand the topic well. You must
save the PHP file with a .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

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.
o PHP is an interpreted language, i.e. there is no need for compilation.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.

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.
o PHP is an interpreted language, i.e. there is no need for compilation.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.

PHP Features

There are given many features of PHP.

Performance: Script written in PHP executes much faster then those scripts written in
other languages such as JSP & ASP.

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.

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.

Compatibility: PHP is compatible with almost all local servers used today like Apache, IIS
etc.
Embedded: PHP code can be easily embedded within HTML tags and script.

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:

Hello First PHP

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.

The syntax of PHP echo is given below:

1. void echo ( string $arg1 [, string $... ] )  

PHP echo statement can be used to print string, multi line strings, escaping characters,
variable, array etc.

PHP echo: printing string


File: echo1.php
1. <?php  
2. echo "Hello by PHP echo";  
3. ?>  

Output:

Hello by PHP echo

PHP echo: printing multi line string


File: echo2.php
1. <?php  
2. echo "Hello by PHP echo  
3. this is multi line  
4. text printed by   
5. PHP echo statement  
6. ";  
7. ?>  

Output:

Hello by PHP echo this is multi line text printed by PHP echo statement

PHP echo: printing escaping characters


File: echo3.php
1. <?php  
2. echo "Hello escape \"sequence\" characters";  
3. ?>  

Output:

Hello escape "sequence" characters

PHP echo: printing variable value


File: echo4.php
1. <?php  
2. $msg="Hello JavaTpoint PHP";  
3. echo "Message is: $msg";    
4. ?>  
Output:

Message is: Hello JavaTpoint PHP


next →← prev

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.

The syntax of PHP print is given below:

1. int print(string $arg)  

PHP print statement can be used to print string, multi line strings, escaping characters,
variable, array etc.

PHP print: printing string


File: print1.php
1. <?php  
2. print "Hello by PHP print ";  
3. print ("Hello by PHP print()");  
4. ?>  

Output:

Hello by PHP print Hello by PHP print()

PHP print: printing multi line string


File: print2.php
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

PHP print: printing escaping characters


File: print3.php
1. <?php  
2. print "Hello escape \"sequence\" characters by PHP print";  
3. ?>  

Output:

Hello escape "sequence" characters by PHP print

PHP print: printing variable value


File: print4.php
1. <?php  
2. $msg="Hello print() in PHP";  
3. print "Message is: $msg";    
4. ?>  

Output:

Message is: Hello print() in PHP

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.

In PHP, a variable is declared using $ sign followed by variable name.

Syntax of declaring a variable in PHP is given below:

1. $variablename=value;  

PHP Variable: Declaring string, integer and float


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

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

Output:

string is: hello string


integer is: 200
float is: 44.6

PHP Variable: Sum of two variables


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

Output:

11

PHP Variable: case sensitive


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

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

PHP Variable: Rules


PHP variables must start with letter or underscore only.

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

File: variablevalid.php
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:

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


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

PHP $ and $$ Variables


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

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

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


Example 1
1. <?php  
2. $x = "abc";  
3. $$x = 200;  
4. echo $x."<br/>";  
5. echo $$x."<br/>";  
6. echo $abc;  
7. ?>  

Output:

In the above example, we have assigned a value to the variable x as abc. Value of


reference variable $$x is assigned as 200.

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

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

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


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.

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:

1. Using define() function


2. Using const keyword

PHP constants follow the same PHP variable rules. For example, it can be started with letter
or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

PHP constant: define()


Let's see the syntax of define() function in PHP.

1. define(name, value, case-insensitive)  

1. name: specifies the constant name


2. value: specifies the constant value
3. case-insensitive: Default value is false. It means it is case sensitive by default.
Let's see the example to define PHP constant using define().

File: constant1.php
1. <?php  
2. define("MESSAGE","Hello JavaTpoint PHP");  
3. echo MESSAGE;  
4. ?>  

Output:

Hello JavaTpoint PHP


File: constant2.php
1. <?php  
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive  
3. echo MESSAGE;  
4. echo message;  
5. ?>  

Output:

Hello JavaTpoint PHPHello JavaTpoint PHP


File: constant3.php
1. <?php  
2. define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive  
3. echo MESSAGE;  
4. echo message;  
5. ?>  

Output:

Hello JavaTpoint PHP


Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
message

PHP constant: const keyword


The const keyword defines constants at compile time. It is a language construct not a
function.

It is bit faster than define().

It is always case sensitive.

File: constant4.php
1. <?php  
2. const MESSAGE="Hello const by JavaTpoint PHP";  
3. echo MESSAGE;  
4. ?>  

Output:

Hello const by JavaTpoint PHP

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

__LINE__ Represents current line number where it is used.

__FILE__ Represents full path and file name of the file. If it is used inside an include, name
returned.

__DIR__ Represents full directory path of the file. Equivalent to dirname(__file__). It does
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
return blank.

__CLASS__ Represents the class name where it is used. If it is used outside of any function,
blank.

__TRAIT__ Represents the trait name where it is used. If it is used outside of any function, t
blank. It includes namespace it was declared in.

__METHOD__ Represents the name of the class method where it is used. The method name is
declared.

__NAMESPACE__ Represents the name of the current namespace.


Example
Let's see an example for each of the above magical constants.

File Name: magic.php

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

PHP Data Types: Scalar Types


There are 4 scalar data types in PHP.

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

PHP Data Types: Compound Types


There are 2 compound data types in PHP.

1. array
2. object

PHP Data Types: Special Types


There are 2 special data types in PHP.

1. resource
2. NULL

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

Output:

PHP is_bool() function


By using this function, we can check whether the variable is boolean variable or not.

Syntax
1. bool is_bool ( mixed $var )  

Parameters

Parameter Description Is compuls

var_name The variable being evaluated. compulso

Returns
It return True if var is boolean, False otherwise.

Example 1
1. <?php  
2.     $x=false;  
3.     echo is_bool($x);  
4. ?>  
Output:

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

Output:

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

Output:

PHP is_int() function


By using this function, we can check the input variable is integer or not. This function
was introduced in PHP 4.0.

Syntax
1. bool is_int (mixed $var)  

Parameters

Parameter Description Is compulsory

var_name The variable being checked. compulsory

Return type
This function returns true if var_name is an integer, Otherwise false.

Example 1
1. <?php  
2.     $x=123;  
3.     echo is_int($x);  
4. ?>  

Output:
Example 2

<?php   
    $x = 56;   
    $y = "xyz";   
    
    if (is_int($x))   
    {   
        echo "$x is Integer \n" ;   
    }   
    else  
    {   
        echo "$x is not an Integer \n" ;   
    }   
    if (is_int($y))   
    {   
        echo "$y is Integer \n" ;   
    }   
    else  
    {   
        echo "$y is not Integer \n" ;   
    }   
?>  

Output:

Example 3
<?php   
    
    $check = 12345;  
    if( is_int($check ))   
    {  
            echo $check . " is an int!";  
    }   
    else   
    {  
            echo $check . " is not an int!";  
    }  
    
?>   

Output:

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

Example 2
1. <?php   
2.     $a = 11.365;  
3.     var_dump($a);  
4. ?>  

Output:

Example 3
<?php  
    $a = 6.203;  
    $b = 2.3e4;  
    $c = 7E-10;  
    var_dump($a);  
    var_dump($b);  
    var_dump($c);  
?>  

Output:

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 )  

Parameters

Parameter Description Is compuls

var The variable being evaluated. compulsory

Return type:
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);  
4. ?>  

Output:

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:

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.

SYNTAX OF ARRAY DECLARATION:


1. Variable_name = array (element1, element2, element3, element4......)  

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:
At first, we must declare a class of object. A class is a structure which consists of properties
and methods. Classes are specified with the class keyword. We specify the data type in the
object class, and then we use the data type in instances of that class.

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

PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. For example:

1. $num=10+20;//+ is the operator and 10,20 are operands  

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

PHP Operators can be categorized in following forms:

o Arithmetic Operators
o 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:

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


o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".

PHP Operators Precedence


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

Operators Additional Associativity


Information

clone new clone and new non-associative

[ array() left

** arithmetic right

++ -- ~ (int) (float) (string) (array) increment/decrement right


(object) (bool) @ and types

instanceof types non-associative

! logical (negation) right

*/% arithmetic left

+-. arithmetic and string left


concatenation
<< >> bitwise (shift) left

< <= > >= comparison non-associative

== != === !== <> comparison non-associative

& bitwise AND left

^ bitwise XOR left

| bitwise OR left

&& logical AND left

|| logical OR left

?: ternary left

= += -= *= **= /= .= %= &= |= assignment right


^= <<= >>= =>

and logical left

xor logical left

or logical left

, many uses (comma) left

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

PHP Single Line Comments


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

o // (C++ style single line comment)


o # (Unix Shell style single line comment)

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:

Welcome to PHP single line comments

PHP Multi Line Comments


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

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:

Welcome to PHP multi line comment

PHP If Else
PHP if else statement is used to test condition. There are various ways to use if statement in
PHP.
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:

12 is less than 100


next →← prev

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:

12 is less than 100

PHP If-else Statement


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

Syntax
if(condition){  
//code to be executed if true  
}else{  
//code to be executed if false  
}  

Flowchart
Example

<?php  
$num=12;  
if($num%2==0){  
echo "$num is even number";  
}else{  
echo "$num is odd number";  
}  
?>  

Output:

12 is even number
PHP 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. }  

PHP Switch Flowchart


PHP Switch Example

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

PHP For Loop


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

It should be used if number of iteration is known otherwise use while loop.

Syntax

1. for(initialization; condition; increment/decrement){  
2. //code to be executed  
3. }  

Flowchart
Example

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

Output:

1
2
3
4
5
6
7
8
9
10

PHP Nested For Loop


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

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

1. foreach( $array as $var ){  
2.  //code to be executed  
3. }  
4. ?>  
Example

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

Output:

Season is: summer


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

PHP While Loop


PHP while loop can be used to traverse set of code like for loop.

It should be used if number of iteration is not known.

Syntax

1. while(condition){  
2. //code to be executed  
3. }  

Alternative Syntax

while(condition):  
//code to be executed  
  
endwhile;  

PHP While Loop Flowchart

PHP While Loop Example

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

Output:

1
2
3
4
5
6
7
8
9
10

Alternative Example

<?php  
$n=1;  
while($n<=10):  
echo "$n<br/>";  
$n++;  
endwhile;  
?>  

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

<?php  
$i=1;  
while($i<=3){  
$j=1;  
while($j<=3){  
echo "$i   $j<br/>";  
$j++;  
}  
$i++;  
}  
?>  

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

PHP do while loop


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

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

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

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

PHP Break: inside inner loop


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

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 Break: inside switch statement


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

<?php      
$num=200;      
switch($num){      
case 100:      
echo("number is equals to 100");      
break;      
case 200:      
echo("number is equal to 200");      
break;      
case 50:      
echo("number is equal to 300");      
break;      
default:      
echo("number is not equal to 100, 200 or 500");      
}     
?>      
Output:

number is equal to 200

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.

Advantage of PHP Functions


Code Reusability: PHP functions are defined only once and can be invoked many times,
like in other programming languages.

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.

Easy to understand: PHP functions separate the programming logic. So it is easier to


understand the flow of the application because every logic is divided in the form of
functions.

PHP User-defined Functions


We can declare and call user-defined functions easily. Let's see the syntax to declare user-
defined functions.

Syntax
1. function functionname(){  
2. //code to be executed  
3. }  

PHP Functions Example


File: function1.php
1. <?php  
2. function sayHello(){  
3. echo "Hello PHP Function";  
4. }  
5. sayHello();//calling function  
6. ?>  

Output:

Hello PHP Function

PHP Function Arguments


We can pass the information in PHP function through arguments which is separated by
comma.

PHP supports Call by Value (default), Call by Reference, Default argument


values and Variable-length argument list.

Let's see the example to pass single argument in PHP function.

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

Let's see the example to pass two argument in PHP function.

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:

Hello Sonoo, you are 27 years old


Hello Vimal, you are 29 years old
Hello John, you are 23 years old

PHP Call By Reference


Value passed to the function doesn't modify the actual value by default (call by value). But
we can do so by passing value as a reference.

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.

Let's see a simple example of call by reference in PHP.

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:

Hello Call By Reference

PHP Function: Default Argument Value


We can specify a default argument value in function. While calling PHP function if you don't
specify any argument, it will take the default argument. Let's see a simple example of using
default argument value in PHP function.

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

PHP Function: Returning Value


Let's see an example of PHP function that returns value.

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.

PHP Parameterized Example 1


Addition and Subtraction

In this example, we have passed two parameters $x and $y inside two


functions add() and sub().

<!DOCTYPE html>  
<html>  
<head>  
    <title>Parameter Addition and Subtraction Example</title>  
</head>  
<body>  
<?php  
        //Adding two numbers  
         function add($x, $y) {  
            $sum = $x + $y;  
            echo "Sum of two numbers is = $sum <br><br>";  
         }   
         add(467, 943);  
  
         //Subtracting two numbers  
         function sub($x, $y) {  
            $diff = $x - $y;  
            echo "Difference between two numbers is = $diff";  
         }   
         sub(943, 467);  
      ?>  
</body>  
</html>  

Output:

PHP Parameterized Example 2


Addition and Subtraction with Dynamic number
In this example, we have passed two parameters $x and $y inside two
functions add() and sub().

<?php  
//add() function with two parameter  
function add($x,$y)    
{  
$sum=$x+$y;  
echo "Sum = $sum <br><br>";  
}  
//sub() function with two parameter  
function sub($x,$y)    
{  
$sub=$x-$y;  
echo "Diff = $sub <br><br>";  
}  
//call function, get  two argument through input box and click on add or sub button  
if(isset($_POST['add']))  
{  
//call add() function  
 add($_POST['first'],$_POST['second']);  
}     
if(isset($_POST['sub']))  
{  
//call add() function  
sub($_POST['first'],$_POST['second']);  
}  
?>  
<form method="post">  
Enter first number: <input type="number" name="first"/><br><br>  
Enter second number: <input type="number" name="second"/><br><br>  
<input type="submit" name="add" value="ADDITION"/>  
<input type="submit" name="sub" value="SUBTRACTION"/>  
</form>     

Output:
We passed the following number,

Now clicking on ADDITION button, we get the following output.


Now clicking on SUBTRACTION button, we get the following output.

PHP Call By Value


PHP allows you to call function by value and reference both. In case of PHP call by value,
actual value is not modified if it is modified inside the function.

Let's understand the concept of call by value by the help of examples.

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.

<?php  
function adder($str2)  
{  
    $str2 .= 'Call By Value';  
}  
$str = 'Hello ';  
adder($str);  
echo $str;  
?>  

Output:

Hello

Example 2
Let's understand PHP call by value concept through another example.

<?php  
function increment($i)  
{  
    $i++;  
}  
$i = 10;  
increment($i);  
echo $i;  
?>  

Output:

10

PHP Call By Reference


In case of PHP call by reference, actual value is modified if it is modified inside the function.
In such case, you need to use & (ampersand) symbol with formal arguments. The &
represents reference of the variable.

Let's understand the concept of call by reference by the help of examples.

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.

<?php  
function adder(&$str2)  
{  
    $str2 .= 'Call By Reference';  
}  
$str = 'This is ';  
adder($str);  
echo $str;  
?>  

Output:

This is Call By Reference

Example 2
Let's understand PHP call by reference concept through another example.

<?php  
function increment(&$i)  
{  
    $i++;  
}  
$i = 10;  
increment($i);  
echo $i;  
?>  

Output:

11

PHP Default Argument Values Function


PHP allows you to define C++ style default argument values. In such case, if you don't pass
any value to the function, it will use default argument value.

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

Example 2
<?php    
function greeting($first="Sonoo",$last="Jaiswal"){    
echo "Greeting: $first $last<br/>";    
}    
greeting();  
greeting("Rahul");  
greeting("Michael","Clark");  
?>    

Output:

Greeting: Sonoo Jaiswal


Greeting: Rahul Jaiswal
Greeting: Michael Clark

Example 3
<?php  
function add($n1=10,$n2=10){  
$n3=$n1+$n2;  
echo "Addition is: $n3<br/>";  
}  
add();  
add(20);  
add(40,40);  
?>  

Output:

Addition is: 20
Addition is: 30
Addition is: 80

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 so, 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.

Let's see a simple example of PHP variable length argument function.

<?php  
function add(...$numbers) {  
    $sum = 0;  
    foreach ($numbers as $n) {  
        $sum += $n;  
    }  
    return $sum;  
}  
  
echo add(1, 2, 3, 4);  
?>  

Output:

10

PHP Recursive Function


PHP also supports recursive function call like C/C++. In such case, we call current function
within function. It is also known as recursion.

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.

Example 1: Printing number


<?php    
function display($number) {    
    if($number<=5){    
     echo "$number <br/>";    
     display($number+1);    
    }  
}    
    
display(1);    
?>    

Output:

1
2
3
4
5

Example 2 : Factorial Number


<?php    
function factorial($n)    
{    
    if ($n < 0)    
        return -1; /*Wrong value*/    
    if ($n == 0)    
        return 1; /*Terminating condition*/    
    return ($n * factorial ($n -1));    
}    
    
echo factorial(5);    
?>    

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.

Advantage of PHP Array


Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.

PHP Array Types


There are 3 types of array in PHP.

1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number, string and
object in the PHP array. All PHP array elements are assigned to an index number by default.

There are two ways to define indexed array:

1st way:

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

2nd way:

$season[0]="summer";  
$season[1]="winter";  
$season[2]="spring";  
$season[3]="autumn";  

Example
File: array1.php
<?php  
$season=array("summer","winter","spring","autumn");  
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  
?>  
Output:

Season are: summer, winter, spring and autumn


File: array2.php
<?php  
$season[0]="summer";  
$season[1]="winter";  
$season[2]="spring";  
$season[3]="autumn";  
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  
?>  

Output:

Season are: summer, winter, spring and autumn

PHP Indexed Array


PHP indexed array is an array which is represented by an index number by default. All
elements of array are represented by an index number which starts from 0.

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

next →← prev

PHP Indexed Array


PHP indexed array is an array which is represented by an index number by default. All
elements of array are represented by an index number which starts from 0.
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:

$size=array("Big","Medium","Short");  

2nd way:

$size[0]="Big";  
$size[1]="Medium";  
$size[2]="Short";  

PHP Indexed Array Example


File: array1.php
<?php  
$size=array("Big","Medium","Short");  
echo "Size: $size[0], $size[1] and $size[2]";  
?>  

Output:

Size: Big, Medium and Short


File: array2.php
<?php  
$size[0]="Big";  
$size[1]="Medium";  
$size[2]="Short";  
echo "Size: $size[0], $size[1] and $size[2]";  
?>  

Output:

Size: Big, Medium and Short


Traversing PHP Indexed Array
We can easily traverse array in PHP using foreach loop. Let's see a simple example to
traverse all the elements of PHP array.

File: array3.php
<?php  
$size=array("Big","Medium","Short");  
foreach( $size as $s )  
{  
  echo "Size is: $s<br />";  
}  
?>  

Output:

Size is: Big


Size is: Medium
Size is: Short

Count Length of PHP Indexed Array


PHP provides count() function which returns length of an array.

<?php  
$size=array("Big","Medium","Short");  
echo count($size);  
?>  

Output:

PHP Associative Array


We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:


1st way:

$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");  

2nd way:

$salary["Sonoo"]="350000";  
$salary["John"]="450000";  
$salary["Kartik"]="200000";  

Example
File: arrayassociative1.php
<?php    
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");    
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  
echo "John salary: ".$salary["John"]."<br/>";  
echo "Kartik salary: ".$salary["Kartik"]."<br/>";  
?>    

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000
File: arrayassociative2.php
<?php    
$salary["Sonoo"]="350000";    
$salary["John"]="450000";    
$salary["Kartik"]="200000";    
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  
echo "John salary: ".$salary["John"]."<br/>";  
echo "Kartik salary: ".$salary["Kartik"]."<br/>";  
?>    

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000

PHP Multidimensional Array


PHP multidimensional array is also known as array of arrays. It allows you to store tabular
data in an array. PHP multidimensional array can be represented in the form of matrix which
is represented by row * column.

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

<?php    
$emp = array  
  (  
  array(1,"sonoo",400000),  
  array(2,"john",500000),  
  array(3,"rahul",300000)  
  );  
  
for ($row = 0; $row < 3; $row++) {  
  for ($col = 0; $col < 3; $col++) {  
    echo $emp[$row][$col]."  ";  
  }  
  echo "<br/>";  
}  
?>    

Output:

1 sonoo 400000
2 john 500000
3 rahul 300000

PHP Array Functions


PHP provides various array functions to access and manipulate the elements of array. The
important PHP array functions are given below.

1) PHP array() function


PHP array() function creates and returns an array. It allows you to create indexed,
associative and multidimensional arrays.

Syntax

array array ([ mixed $... ] )  

Example

<?php    
$season=array("summer","winter","spring","autumn");    
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";    
?>    

Output:

Season are: summer, winter, spring and autumn

2) PHP array_change_key_case() function


PHP array_change_key_case() function changes the case of all key of an array.

Note: It changes case of key only.

Syntax

array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )  
Example

<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");    
print_r(array_change_key_case($salary,CASE_UPPER));   
?>    

Output:

Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )

Example

<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");    
print_r(array_change_key_case($salary,CASE_LOWER));   
?>    

Output:

Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )

3) PHP array_chunk() function


PHP array_chunk() function splits array into chunks. By using array_chunk() method, you
can divide array into many parts.

Syntax

array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )  

Example

<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");    
print_r(array_chunk($salary,2));   
?>    

Output:

Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)
4) PHP count() function
PHP count() function counts all elements in an array.

Syntax

int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )  

Example

<?php    
$season=array("summer","winter","spring","autumn");    
echo count($season);    
?>    

Output:

5) PHP sort() function


PHP sort() function sorts all the elements in an array.

Syntax

bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )  

Example

<?php    
$season=array("summer","winter","spring","autumn");    
sort($season);  
foreach( $season as $s )    
{    
  echo "$s<br />";    
}    
?>    

Output:

autumn
spring
summer
winter
6) PHP array_reverse() function
PHP array_reverse() function returns an array containing elements in reversed order.

Syntax

array array_reverse ( array $array [, bool $preserve_keys = false ] )  

Example

<?php    
$season=array("summer","winter","spring","autumn");    
$reverseseason=array_reverse($season);  
foreach( $reverseseason as $s )    
{    
  echo "$s<br />";    
}    
?>    

Output:

autumn
spring
winter
summer

7) PHP array_search() function


PHP array_search() function searches the specified value in an array. It returns key if
search is successful.

Syntax

mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )  

Example

<?php    
$season=array("summer","winter","spring","autumn");    
$key=array_search("spring",$season);  
echo $key;    
?>    

Output:
2

8) PHP array_intersect() function


PHP array_intersect() function returns the intersection of two array. In other words, it
returns the matching elements of two array.

Syntax

array array_intersect ( array $array1 , array $array2 [, array $... ] )  

Example

<?php    
$name1=array("sonoo","john","vivek","smith");    
$name2=array("umesh","sonoo","kartik","smith");    
$name3=array_intersect($name1,$name2);  
foreach( $name3 as $n )    
{    
  echo "$n<br />";    
}    
?>    

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
o newdoc syntax (since PHP 5.3)

Single Quoted PHP String


We can create a string in PHP by enclosing text in a single quote. It is the easiest way to specify string in
PHP.

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:

Hello text multiple line text within single quoted string


Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string

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:

trying variable $num1


trying backslash n and backslash t inside single quoted string \n \t
Using single quote 'my quote' and \backslash

Double Quoted PHP String


In PHP, we can specify string through enclosing text within double quote also. But escape sequences and
variables will be interpreted using double quote PHP strings.

1. <?php  
2. $str="Hello text within double quote";  
3. echo $str;  
4. ?>  

Output:

Hello text within double quote

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:

Parse error: syntax error, unexpected 'quote' (T_STRING) in C:\wamp\www\string1.php on


line 2

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:

Hello text multiple line text within double quoted string


Using double "quote" with backslash inside double quoted string
Using escape sequences in double quoted string

In double quoted strings, variable will be interpreted.

1. <?php  
2. $num1=10;   
3. echo "Number is: $num1";  
4. ?>  

Output:

Number is: 10

PHP Form Handling


We can create and use forms in PHP. To get form data, we need to use PHP superglobals
$_GET and $_POST.

The form request may be get or post. To retrieve data from get request, we need to use
$_GET, for post request $_POST.

PHP Get Form


Get request is the default form request. The data passed through get request is visible on
the URL browser so it is not secured. You can send limited amount of data through get
request.

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

PHP Post Form


Post request is widely used to submit form that have large amount of data such as file
upload, image upload, login form, registration form etc.

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
<form action="login.php" method="post">   
<table>   
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>  
<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr
>   
<tr><td colspan="2"><input type="submit" value="login"/>  </td></tr>  
</table>  
</form>   
File: login.php
<?php  
$name=$_POST["name"];//receiving name field value in $name variable  
$password=$_POST["password"];//receiving password field value in $password variable  
  
echo "Welcome: $name, your password is: $password";  
?>  

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.

PHP include example


PHP include is used to include file on the basis of given path. You may use relative or
absolute path of the file. Let's see a simple PHP include example.

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: include1.php
1. <?php include("menu.html"); ?>  
2. <h1>This is Main Page</h1>  

Output:

Home | PHP | Java | HTML

This is Main Page


PHP require example
PHP require is similar to include. Let's see a simple PHP require example.

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:

Home | PHP | Java | HTML

This is Main Page

PHP File Handling


PHP File System allows us to create file, read file line by line, read file character by
character, write file, append file, delete file and close file.

PHP Open File - fopen()


The PHP fopen() function is used to open a file.

Syntax

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, res
ource $context ]] )  

Example

<?php  
$handle = fopen("c:\\folder\\file.txt", "r");  
?>  

PHP Close File - fclose()


The PHP fclose() function is used to close an open file pointer.

Syntax

1. ool fclose ( resource $handle )  

Example

1. <?php  
2. fclose($handle);  
3. ?>  

PHP Read File - fread()


The PHP fread() function is used to read the content of the file. It accepts two arguments:
resource and file size.

Syntax

1. string fread ( resource $handle , int $length )  

Example

<?php    
$filename = "c:\\myfile.txt";    
$handle = fopen($filename, "r");//open file in read mode    
  
$contents = fread($handle, filesize($filename));//read file    
  
echo $contents;//printing data of file  
fclose($handle);//close file    
?>    

Output

hello php file

PHP Read File


PHP provides various functions to read data from file. There are different functions that
allow you to read all file data, read data line by line and read data character by character.

The available PHP file read functions are given below.

o fread()
o fgets()
o fgetc()

PHP Read File - fread()


The PHP fread() function is used to read data of the file. It requires two arguments: file
resource and file size.

Syntax
1. string fread (resource $handle , int $length )  

$handle represents file pointer that is created by fopen() function.

$length represents length of byte to be read.

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

this is first line


this is another line
this is third line

PHP Read File - fgets()


The PHP fgets() function is used to read single line from the file.

Syntax
1. string fgets ( resource $handle [, int $length ] )  

Example
1. <?php    
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode    
3. echo fgets($fp);  
4. fclose($fp);  
5. ?>    

Output

this is first line

PHP Read File - fgetc()


The PHP fgetc() function is used to read single character from the file. To get all data using
fgetc() function, use !feof() function inside the while loop.

Syntax
1. string fgetc ( resource $handle )  

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

this is first line this is another line this is third line

PHP Write File - fwrite()


The PHP fwrite() function is used to write content of the string into file.

Syntax

1. int fwrite ( resource $handle , string $string [, int $length ] )  

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

File written successfully


next →← prev

PHP Write File


PHP fwrite() and fputs() functions are used to write data into file. To write data into file,
you need to use w, r+, w+, x, x+, c or c+ mode.
PHP Write File - fwrite()
The PHP fwrite() function is used to write content of the string into file.

Syntax

1. int fwrite ( resource $handle , string $string [, int $length ] )  

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

welcome to php file write

PHP Overwriting File


If you run the above code again, it will erase the previous data of the file and writes the
new data. Let's see the code that writes only new data into data.txt file.

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.

PHP Append to File


You can append data into file by using a or a+ mode in fopen() function. Let's see a simple
example that appends data into data.txt file.

Let's see the data of file first.

data.txt

welcome to php file write

PHP Append to File - fwrite()


The PHP fwrite() function is used to write and append data into file.

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

welcome to php file write this is additional text appending data

PHP Delete File - unlink()


The PHP unlink() function is used to delete file.

Syntax

bool unlink ( string $filename [, resource $context ] )  

Example
<?php    
unlink('data.txt');  
   
echo "File deleted successfully";  
?>  

PHP MySQL Connect


Since PHP 5.5, mysql_connect() extension is deprecated. Now it is recommended to use
one of the 2 alternatives.

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)  

next →← prev

PHP MySQL Connect


Since PHP 5.5, mysql_connect() extension is deprecated. Now it is recommended to
use one of the 2 alternatives.

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)  

PHP MySQL Connect Example


Example

<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$conn = mysqli_connect($host, $user, $pass);  
if(! $conn )  
{  
  die('Could not connect: ' . mysqli_error());  
}  
echo 'Connected successfully';  
mysqli_close($conn);  
?>  

Output:

Connected successfully

PHP MySQL Create Database


Since PHP 4.3, mysql_create_db() function is deprecated. Now it is recommended to use
one of the 2 alternatives.

o mysqli_query()
o PDO::__query()

PHP MySQLi Create Database Example


Example
<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$conn = mysqli_connect($host, $user, $pass);  
if(! $conn )  
{  
  die('Could not connect: ' . mysqli_connect_error());  
}  
echo 'Connected successfully<br/>';  
  
$sql = 'CREATE Database mydb';  
if(mysqli_query( $conn,$sql)){  
  echo "Database mydb created successfully.";  
}else{  
echo "Sorry, database creation failed ".mysqli_error($conn);  
}  
mysqli_close($conn);  
?>  

Output:

Connected successfully
Database mydb created successfully.

PHP MySQL Create Table


PHP mysql_query() function is used to create table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.

o mysqli_query()
o PDO::__query()
PHP MySQLi Create Table Example
Example
<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$dbname = 'test';  
  
$conn = mysqli_connect($host, $user, $pass,$dbname);  
if(!$conn){  
  die('Could not connect: '.mysqli_connect_error());  
}  
echo 'Connected successfully<br/>';  
  
$sql = "create table emp5(id INT AUTO_INCREMENT,name VARCHAR(20) NOT NULL,  
emp_salary INT NOT NULL,primary key (id))";  
if(mysqli_query($conn, $sql)){  
 echo "Table emp5 created successfully";  
}else{  
echo "Could not create table: ". mysqli_error($conn);  
}  
  
mysqli_close($conn);  
?>  

Output:

Connected successfully
Table emp5 created successfully

PHP MySQL Insert Record


PHP mysql_query() function is used to insert record in a table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.

o mysqli_query()
o PDO::__query()

PHP MySQLi Insert Record Example


Example
<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$dbname = 'test';  
  
$conn = mysqli_connect($host, $user, $pass,$dbname);  
if(!$conn){  
  die('Could not connect: '.mysqli_connect_error());  
}  
echo 'Connected successfully<br/>';  
  
$sql = 'INSERT INTO emp4(name,salary) VALUES ("sonoo", 9000)';  
if(mysqli_query($conn, $sql)){  
 echo "Record inserted successfully";  
}else{  
echo "Could not insert record: ". mysqli_error($conn);  
}  
  
mysqli_close($conn);  
?>  

Output:

Connected successfully
Record inserted successfully

PHP MySQL Update Record


PHP mysql_query() function is used to update record in a table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.

o mysqli_query()
o PDO::__query()

PHP MySQLi Update Record Example


Example
<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$dbname = 'test';  
  
$conn = mysqli_connect($host, $user, $pass,$dbname);  
if(!$conn){  
  die('Could not connect: '.mysqli_connect_error());  
}  
echo 'Connected successfully<br/>';  
  
$id=2;  
$name="Rahul";  
$salary=80000;  
$sql = "update emp4 set name=\"$name\", salary=$salary where id=$id";  
if(mysqli_query($conn, $sql)){  
 echo "Record updated successfully";  
}else{  
echo "Could not update record: ". mysqli_error($conn);  
}  
  
mysqli_close($conn);  
?>  

Output:

Connected successfully
Record updated successfully

PHP MySQL Delete Record


PHP mysql_query() function is used to delete record in a table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.

o mysqli_query()
o PDO::__query()

PHP MySQLi Delete Record Example


Example
<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$dbname = 'test';  
  
$conn = mysqli_connect($host, $user, $pass,$dbname);  
if(!$conn){  
  die('Could not connect: '.mysqli_connect_error());  
}  
echo 'Connected successfully<br/>';  
  
$id=2;  
$sql = "delete from emp4 where id=$id";  
if(mysqli_query($conn, $sql)){  
 echo "Record deleted successfully";  
}else{  
echo "Could not deleted record: ". mysqli_error($conn);  
}  
  
mysqli_close($conn);  
?>  

Output:

Connected successfully
Record deleted successfully

PHP MySQL Select Query


PHP mysql_query() function is used to execute select query. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.

o mysqli_query()
o PDO::__query()

There are two other MySQLi functions used in select query.

o mysqli_num_rows(mysqli_result $result): returns number of rows.


o mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array.
Each key of the array represents the column name of the table. It return NULL if
there are no more rows.

PHP MySQLi Select Query Example


Example
<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$dbname = 'test';  
$conn = mysqli_connect($host, $user, $pass,$dbname);  
if(!$conn){  
  die('Could not connect: '.mysqli_connect_error());  
}  
echo 'Connected successfully<br/>';  
  
$sql = 'SELECT * FROM emp4';  
$retval=mysqli_query($conn, $sql);  
  
if(mysqli_num_rows($retval) > 0){  
 while($row = mysqli_fetch_assoc($retval)){  
    echo "EMP ID :{$row['id']}  <br> ".  
         "EMP NAME : {$row['name']} <br> ".  
         "EMP SALARY : {$row['salary']} <br> ".  
         "--------------------------------<br>";  
 } //end of while  
}else{  
echo "0 results";  
}  
mysqli_close($conn);  
?>  

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

PHP MySQL Order By


PHP mysql_query() function is used to execute select query with order by clause. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.

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.

1. SELECT * FROM emp4 order by name  

Let's see the query to select data from emp4 table in descending order on the basis of name
column.

1. SELECT * FROM emp4 order by name desc  

PHP MySQLi Order by Example


Example
<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$dbname = 'test';  
$conn = mysqli_connect($host, $user, $pass,$dbname);  
if(!$conn){  
  die('Could not connect: '.mysqli_connect_error());  
}  
echo 'Connected successfully<br/>';  
  
$sql = 'SELECT * FROM emp4 order by name';  
$retval=mysqli_query($conn, $sql);  
  
if(mysqli_num_rows($retval) > 0){  
 while($row = mysqli_fetch_assoc($retval)){  
    echo "EMP ID :{$row['id']}  <br> ".  
         "EMP NAME : {$row['name']} <br> ".  
         "EMP SALARY : {$row['salary']} <br> ".  
         "--------------------------------<br>";  
 } //end of while  
}else{  
echo "0 results";  
}  
mysqli_close($conn);  
?>  

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

You might also like