PHP Notes
PHP Notes
PHP Notes
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
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:
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.
1. void echo ( string $arg1 [, string $... ] )
PHP echo statement can be used to print string, multi line strings, escaping characters,
variable, array etc.
Output:
Output:
Hello by PHP echo this is multi line text printed by PHP echo statement
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.
1. int print(string $arg)
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:
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:
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:
PHP constants follow the same PHP variable rules. For example, it can be started with letter
or underscore only.
1. define(name, value, case-insensitive)
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, 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.
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:
1. boolean
2. integer
3. float
4. string
1. array
2. object
1. resource
2. NULL
Boolean
These data types provide output as 0 or 1. In PHP, value of True is one and the value of
False is nothing.
Syntax
1. <?php
2. $foo = True; // assign the value TRUE to $foo
3. ?>
Example 1
1. <?php
2. $a=true;
3. echo $a;
4. ?>
Output:
Syntax
1. bool is_bool ( mixed $var )
Parameters
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:
Syntax
1. bool is_int (mixed $var)
Parameters
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:
Syntax
1. bool is_float ( mixed $var )
Parameters
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.
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.
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
[ 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:
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
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. }
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
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
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. 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:
Syntax
1. while(condition){
2. //code to be executed
3. }
Alternative Syntax
while(condition):
//code to be executed
endwhile;
<?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
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
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
1. <?php
2. for($i=1;$i<=10;$i++){
3. echo "$i <br/>";
4. if($i==5){
5. break;
6. }
7. }
8. ?>
Output:
1
2
3
4
5
1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){
4. echo "$i $j<br/>";
5. if($i==2 && $j==2){
6. break;
7. }
8. }
9. }
10. ?>
Output:
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
<?php
$num=200;
switch($num){
case 100:
echo("number is equals to 100");
break;
case 200:
echo("number is equal to 200");
break;
case 50:
echo("number is equal to 300");
break;
default:
echo("number is not equal to 100, 200 or 500");
}
?>
Output:
PHP 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.
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. }
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
They are specified inside the parentheses, after the function name.
The output depends upon the dynamic values passed as the parameters into the function.
<!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
//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,
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
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:
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
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:
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
The 3 dot concept is implemented for variable length argument since PHP 5.6.
<?php
function add(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum;
}
echo add(1, 2, 3, 4);
?>
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
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:
$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:
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";
next →← prev
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";
Output:
Output:
File: array3.php
<?php
$size=array("Big","Medium","Short");
foreach( $size as $s )
{
echo "Size is: $s<br />";
}
?>
Output:
<?php
$size=array("Big","Medium","Short");
echo count($size);
?>
Output:
$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:
Output:
Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );
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
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:
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 )
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:
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
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
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)
1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?>
Output:
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:
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
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
<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:
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.
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
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
Syntax
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, res
ource $context ]] )
Example
<?php
$handle = fopen("c:\\folder\\file.txt", "r");
?>
Syntax
1. ool fclose ( resource $handle )
Example
1. <?php
2. fclose($handle);
3. ?>
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
o fread()
o fgets()
o fgetc()
Syntax
1. string fread (resource $handle , int $length )
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
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
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
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
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
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
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
Syntax
bool unlink ( string $filename [, resource $context ] )
Example
<?php
unlink('data.txt');
echo "File deleted successfully";
?>
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
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
$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
o mysqli_query()
o PDO::__query()
Output:
Connected successfully
Database mydb created successfully.
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
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.
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
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
--------------------------------