Escolar Documentos
Profissional Documentos
Cultura Documentos
1
If you are on Windows and don't want Perl and other Output:
features of XAMPP, you should go for WAMP. In a similar
way, you may use LAMP for Linux and MAMP for Macintosh. Hello First PHP
PHP Example PHP Echo
It is very easy to create a simple PHP example. To do so, PHP echo is a language construct not a function, so you
create a file and write HTML tags + PHP code and save this don't need to use parenthesis with it. But if you want to use
file with .php extension. more than one parameters, it is required to use parenthesis.
All PHP code goes between php tag. Syntax of PHP tag is The syntax of PHP echo is given below:
given below:
void echo ( string $arg1 [, string $... ] )
<?php
PHP echo statement can be used to print string, multi line
//your code here strings, escaping characters, variable, array etc.
?>
PHP echo: printing string
Let's see a simple PHP example where we are writing some
text using PHP echo command. File: echo1.php
<?php
File: first.php echo "Hello by PHP echo";
1. <!DOCTYPE> ?>
2. <html>
3. <body> Output:
4. <?php
Hello by PHP echo
5. echo "<h2>Hello First PHP</h2>";
6. ?> PHP echo: printing multi line string
7. </body>
File: echo2.php
8. </html>
2
<?php ?>
echo "Hello by PHP echo
Output:
this is multi line
text printed by Message is: Hello JavaTpoint PHP
PHP echo statement
";
PHP Print
?>
Like PHP echo, PHP print is a language construct, so you
Output: don't need to use parenthesis with the argument list. Unlike
echo, it always returns 1.
Hello by PHP echo this is multi line text printed by PHP echo
statement The syntax of PHP print is given below:
File: echo3.php PHP print statement can be used to print string, multi line
<?php strings, escaping characters, variable, array etc.
echo "Hello escape \"sequence\" characters";
PHP print: printing string
?>
File: print1.php
Output:
<?php
Hello escape "sequence" characters print "Hello by PHP print ";
print ("Hello by PHP print()");
PHP echo: printing variable value ?>
3
PHP print: printing multi line string <?php
$msg="Hello print() in PHP";
File: print2.php
print "Message is: $msg";
<?php
?>
print "Hello by PHP print
this is multi line Output:
text printed by
Message is: Hello print() in PHP
PHP print statement
"; 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
Output: data temporarily.
Hello by PHP print this is multi line text printed by PHP print In PHP, a variable is declared using $ sign followed by
statement variable name.
PHP print: printing escaping characters Syntax of declaring a variable in PHP is given below:
File: print3.php
$variablename=value;
<?php
print "Hello escape \"sequence\" characters by PHP p A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume).
rint";
?> Rules for PHP variables:
4
Variable names are case-sensitive ($age and $AGE The scope of a variable is the part of the script where the
are two different variables) variable can be referenced/used.
PHP Variable: Declaring string, integer and float PHP has three different variable scopes:
Let's see the example to store string, integer and float local
values in PHP variables. global
static
File: variable1.php
Global and Local Scope
<?php
$str="hello string"; A variable declared outside a function has a GLOBAL
$x=200; SCOPE and can only be accessed outside a function:
$y=44.6;
Example
echo "string is: $str <br/>";
<?php
echo "integer is: $x <br/>";
$x = 5; // global scope
echo "float is: $y <br/>";
?> function myTest() {
// using x inside this function will generate an
Output: error
echo "<p>Variable x inside function is: $x</p>";
string is: hello string }
integer is: 200
myTest();
float is: 44.6
5
A variable declared within a function has a LOCAL SCOPE Example
and can only be accessed within that function:
<?php
Example $x = 5;
$y = 10;
<?php
function myTest() { function myTest() {
$x = 5; // local scope global $x, $y;
echo "<p>Variable x inside function is: $x</p>"; $y = $x + $y;
} }
myTest();
myTest();
// using x outside the function will generate an error echo $y; // outputs 15
echo "<p>Variable x outside function is: $x</p>"; ?>
?>
Output:
15
Output:
PHP also stores all global variables in an array called
Variable x inside function is: 5 $GLOBALS[index]. The index holds the name of the
Variable x outside function is: variable. This array is also accessible from within functions
and can be used to update global variables directly.
Note: You can have local variables with the same name in
The example above can be rewritten like this:
different functions, because local variables are only
recognized by the function in which they are declared. Example
<?php
PHP The global Keyword $x = 5;
$y = 10;
The global keyword is used to access a global variable from
within a function. function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
To do this, use the global keyword before the variables }
(inside the function):
6
myTest(); Then, each time the function is called, that variable will still
echo $y; // outputs 15 have the information it contained from the last time the
?> function was called.
Example PHP constants follow the same PHP variable rules. For
example, it can be started with letter or underscore only.
<?php
function myTest() { Conventionally, PHP constants should be defined in
static $x = 0; uppercase letters.
echo $x;
$x++; PHP constant by using define()
}
Let's see the syntax of define() function in PHP.
myTest();
myTest();
define(name, value, case-insensitive)
myTest();
?> 1. name: specifies the constant name
7
File: constant1.php Output:
<?php
Hello JavaTpoint PHP
define("MESSAGE","Hello JavaTpoint PHP"); Notice: Use of undefined constant message - assumed
echo MESSAGE; 'message'
in C:\wamp\www\vconstant3.php on line 4
?>
message
Output:
PHP constant by using const keyword
Hello JavaTpoint PHP
The const keyword defines constants at compile time. It is a
File: constant2.php language construct not a function.
<?php
It is bit faster than define().
define("MESSAGE","Hello JavaTpoint PHP",true);//no
t case sensitive It is always case sensitive.
echo MESSAGE;
File: constant4.php
echo message;
<?php
?>
const MESSAGE="Hello const by JavaTpoint PHP";
Output: echo MESSAGE;
?>
Hello JavaTpoint PHPHello JavaTpoint PHP
Output:
File: constant3.php
<?php Hello const by JavaTpoint PHP
define("MESSAGE","Hello JavaTpoint PHP",false);//ca
se sensitive PHP Data Types
echo MESSAGE;
echo message; Variables can store data of different types, and different
data types can do different things.
?>
PHP supports the following data types:
8
String An integer must have at least one digit
Integer An integer must not have a decimal point
Float (floating point numbers - also called double) An integer can be either positive or negative
Boolean Integers can be specified in three formats: decimal
Array (10-based), hexadecimal (16-based - prefixed with
Object 0x) or octal (8-based - prefixed with 0)
NULL
Resource In the following example $x is an integer. The PHP
var_dump() function returns the data type and value:
1. PHP String
Example
A string is a sequence of characters, like "Hello world!". A
string can be any text inside quotes. You can use single or <?php
double quotes: $x = 5985;
var_dump($x);
Example ?>
<?php Output
$x = "Hello world!"; int(5985)
$y = 'Hello world!';
9
Output: In PHP, an object must be explicitly declared.
float(10.365)
First we must declare a class of object. For this, we use the
class keyword. A class is a structure that can contain
4. PHP Boolean properties and methods:
$x = true; <?php
$y = false; class Car {
function Car() {
Booleans are often used in conditional testing. $this->model = "VW";
}
5. PHP Array }
6. PHP Object A variable of data type NULL is a variable that has no value
assigned to it.
An object is a data type which stores data and information
on how to process that data. Tip: If a variable is created without a value, it is
automatically assigned a value of NULL.
10
Variables can also be emptied by setting the value to NULL: 1. PHP Arithmetic Operators
Example The PHP arithmetic operators are used with numeric values
to perform common arithmetical operations, such as
<?php addition, subtraction, multiplication etc.
$x = "Hello world!";
$x = null;
Operator Name Example Result
var_dump($x);
?> Sum of $x and
+ Addition $x + $y
$y
Output:
NULL Difference of
- Subtraction $x - $y
$x and $y
8. PHP Resource
Product of $x
The special resource type is not an actual data type. It is * Multiplication $x * $y
and $y
the storing of a reference to functions and resources
external to PHP. Quotient of $x
/ Division $x / $y
and $y
A common example of using the resource data type is a
database call. Remainder of
% Modulus $x % $y $x divided by
PHP Operators $y
Result of
Operators are used to perform operations on variables and
raising $x to
values.
the $y'th
** Exponentiation $x ** $y
power
PHP divides the operators in the following groups: (Introduced in
PHP 5.6)
Arithmetic operators
Assignment operators
Comparison operators 2. PHP Assignment Operators
Increment/Decrement operators
Logical operators
The PHP assignment operators are used with numeric values
String operators
to write a value to a variable.
Array operators
11
The basic assignment operator in PHP is "=". It means that
=== Identical $x === $y Returns true if
the left operand gets set to the value of the assignment
$x is equal to
expression on the right.
$y, and they
are of the same
Assignment Same Description type
as...
!= Not equal $x != $y Returns true if
x=y x=y The left operand gets set
$x is not equal
to the value of the
to $y
expression on the right
<> Not equal $x <> $y Returns true if
x += y x = x + y Addition
$x is not equal
to $y
x -= y x=x-y Subtraction
!== Not $x !== $y Returns true if
x *= y x=x*y Multiplication
identical $x is not equal
to $y, or they
x /= y x=x/y Division
are not of the
same type
x %= y x = x % y Modulus
> Greater $x > $y Returns true if
3. PHP Comparison Operators than $x is greater
than $y
The PHP comparison operators are used to compare two
values (number or string): < Less than $x < $y Returns true if
$x is less than
$y
Operator Name Example Result
>= Greater $x >= $y Returns true if
== Equal $x == $y Returns true if
than or $x is greater
$x is equal to
equal to than or equal to
$y
$y
12
4. PHP Increment / Decrement Operators
xor Xor $x xor $y True if either $x or
$y is true, but not
The PHP increment operators are used to increment a both
variable's value.
&& And $x && $y True if both $x and
The PHP decrement operators are used to decrement a $y are true
variable's value.
|| Or $x || $y True if either $x or
Operator Name Description $y is true
++$x Pre-increment Increments $x by one, then ! Not !$x True if $x is not true
returns $x
and And $x and $y True if both $x and The PHP array operators are used to compare arrays.
$y are true
or Or $x or $y True if either $x or
$y is true
13
Operator Name Example Result PHP Single Line Comments
+ Union $x + $y Union of $x and $y There are two ways to use single line comments in PHP.
14
echo "Welcome to PHP multi line comment"; Flowchart
?>
Output:
CONTROL STATEMENTS
PHP If Else
o if
o if-else
o if-else-if
o nested if Example
15
PHP If-else Statement Example
Flowchart Output:
12 is even number
PHP Switch
Syntax
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
16
...... PHP Switch Example
default:
<?php
code to be executed if all cases are not matched;
$num=20;
}
switch($num){
PHP Switch Flowchart case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Output:
number is equal to 20
PHP for loop can be used to traverse set of code for the
specified number of times.
17
It should be used if number of iteration is known otherwise Example
use while loop.
<?php
Syntax for($n=1;$n<=10;$n++){
echo "$n<br/>";
for(initialization; condition; increment/decrement){ }
//code to be executed ?>
} Output:
1
2
Flowchart
3
4
5
6
7
8
9
10
Example
<?php
for($i=1;$i<=3;$i++){
18
for($j=1;$j<=3;$j++){ $season=array("summer","winter","spring","a
echo "$i $j<br/>"; utumn");
} foreach( $season as $arr ){
} echo "Season is: $arr<br />";
?> }
?>
Output:
Output:
1 1
1 2
Season is: summer
1 3
Season is: winter
2 1
Season is: spring
2 2
Season is: autumn
2 3
3 1 PHP While Loop
3 2
3 3
PHP while loop can be used to traverse set of code like for
loop.
PHP For Each Loop
It should be used if number of iteration is not known.
PHP for each loop is used to traverse array elements.
Syntax
Syntax
while(condition){
foreach( $array as $var ){
//code to be executed
//code to be executed
}
}
?> Alternative Syntax
Example while(condition):
//code to be executed
<?php
endwhile
19
PHP While Loop Flowchart 1
2
3
4
5
6
7
8
9
10
Alternative Example
<?php
$n=1;
while($n<=10):
echo "$n<br/>";
$n++;
endwhile;
?>
<?php 1
2
$n=1; 3
while($n<=10){ 4
5
echo "$n<br/>"; 6
$n++; 7
8
} 9
?> 10
Output:
20
PHP Nested While Loop 2 3
3 1
3 2
We can use while loop inside another while loop in PHP, it is 3 3
known as nested while loop.
PHP do 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 PHP do while loop can be used to traverse set of code like
to be executed for 3 times and nested while loop for 3 php while loop. The PHP do-while loop is guaranteed to run
times, nested while loop will be executed 9 times (3 times at least once.
for 1st outer loop, 3 times for 2nd outer loop and 3 times
for 3rd outer loop). It executes the code at least one time always because
condition is checked after executing the code.
Example
Syntax
<?php
$i=1; do{
$j=1; }while(condition);
while($j<=3){ Flowchart
echo "$i $j<br/>";
$j++;
}
$i++;
}
?>
Output:
1 1
1 2
1 3
2 1
2 2
21
Example Flowchart
<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>
Output:
1
2
3
4
5
6
7
8
9
10
PHP Break: inside loop
PHP Break
Let's see a simple example to break the execution of for
PHP break statement breaks the execution of current for, loop if value of i is equal to 5.
while, do-while, switch and for-each loop. If you use break
inside inner loop, it breaks the execution of inner loop only.
<?php
Syntax for($i=1;$i<=10;$i++){
echo "$i <br/>";
jump statement;
if($i==5){
break;
break;
}
22
2 1
} 2 2
?> 3 1
3 2
Output: 3 3
1 1 Output:
1 2
1 3
number is equal to 200
23
PHP Functions Note: Function name must be start with letter and
underscore only like other labels in PHP. It can't be
PHP function is a piece of code that can be reused many
times. It can take input as argument list and return value. start with numbers or special symbols.
There are thousands of built-in functions in PHP.
24
PHP Parameterized Example
<!DOCTYPE html>
<html>
<head>
<title>Parameter Addition and Subtraction Example</titl
e>
</head>
<body>
<?php
//Adding two numbers PHP Call By Value
function add($x, $y) {
$sum = $x + $y; PHP allows you to call function by value and reference both.
echo "Sum of two numbers is = $sum <br><br>"; In case of PHP call by value, actual value is not modified if it
} is modified inside the function.
add(467, 943);
Let's understand the concept of call by value by the help of
//Subtracting two numbers examples.
function sub($x, $y) {
$diff = $x - $y;
Example
echo "Difference between two numbers is = $diff";
}
sub(943, 467); In this example, variable $str is passed to the adder
?> function where it is concatenated with 'Call By Value' string.
</body> But, printing $str variable results 'Hello' only. It is because
</html> changes are done in the local variable $str2 only. It doesn't
reflect to $str variable.
Output:
25
<?php <?php
function adder($str2) function adder(&$str2)
{ {
$str2 .= 'Call By Value'; $str2 .= 'Call By Reference';
} }
$str = 'Hello '; $str = 'This is ';
adder($str); adder($str);
echo $str; echo $str;
?> ?>
Output: Output:
26
Output: add(40,40);
?>
Hello Sonoo
Hello Ram Output:
Hello Vimal
Addition is: 20
Since PHP 5, you can use the concept of default argument Addition is: 30
value with call by reference also. Addition is: 80
Output: <?php
function add(...$numbers) {
Greeting: Sonoo Jaiswal
Greeting: Rahul Jaiswal $sum = 0;
Greeting: Michael Clark foreach ($numbers as $n) {
$sum += $n;
Example 3 }
<?php return $sum;
function add($n1=10,$n2=10){ }
$n3=$n1+$n2;
echo "Addition is: $n3<br/>"; echo add(1, 2, 3, 4);
}
?>
add();
add(20);
27
Output: Example 2 : Factorial Number
<?php
10 function factorial($n)
{
PHP Recursive Function if ($n < 0)
return -1; /*Wrong value*/
PHP also supports recursive function call like C/C++. In if ($n == 0)
such case, we call current function within function. It is also return 1; /*Terminating condition*/
known as recursion. return ($n * factorial ($n -1));
}
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. echo factorial(5);
?>
Example 1: Printing number
<?php Output:
function display($number) {
120
if($number<=5){
echo "$number <br/>";
display($number+1); 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
display(1); single variable.
?>
Advantage of PHP Array
Output:
Less Code: We don't need to define multiple variables.
1
2 Easy to traverse: By the help of single loop, we can
3 traverse all the elements of an array.
4
5 Sorting: We can sort the elements of array.
28
PHP Array Types PHP Indexed Array Example
PHP indexed array is an array which is represented by an Size: Big, Medium and Short
index number by default. All elements of array are
represented by an index number which starts from 0. File: array2.php
<?php
PHP indexed array can store numbers, strings or any object.
PHP indexed array is also known as numeric array. $size[0]="Big";
$size[1]="Medium";
Definition $size[2]="Short";
echo "Size: $size[0], $size[1] and $size[2]";
There are two ways to define indexed array:
?>
1st way:
Output:
$size=array("Big","Medium","Short");
Size: Big, Medium and Short
2nd way:
Traversing PHP Indexed Array
29
<?php PHP Associative Array
$size=array("Big","Medium","Short");
PHP allows you to associate name/label with each array
foreach( $size as $s ) elements in PHP using => symbol. Such way, you can easily
{ remember the element because each element is
represented by label than an incremented number.
echo "Size is: $s<br />";
} Definition
?>
There are two ways to define associative array:
Output:
1st way:
Size is: Big
Size is: Medium
Size is: Short $salary=array("Sonoo"=>"550000","Vimal"=>"250000","R
atan"=>"200000");
Count Length of PHP Indexed Array
2nd way:
PHP provides count() function which returns length of an
array. $salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
<?php
$salary["Ratan"]="200000";
$size=array("Big","Medium","Short");
echo count($size); Example
?>
File: arrayassociative1.php
Output: <?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000",
3 "Ratan"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>
30
Output:
<?php
Sonoo salary: 550000 $salary=array("Sonoo"=>"550000","Vimal"=>"250000",
Vimal salary: 250000 "Ratan"=>"200000");
Ratan salary: 200000 foreach($salary as $k => $v) {
echo "Key: ".$k." Value: ".$v."<br/>";
File: arrayassociative2.php }
<?php ?>
$salary["Sonoo"]="550000";
Output:
$salary["Vimal"]="250000";
$salary["Ratan"]="200000"; Key: Sonoo Value: 550000
Key: Vimal Value: 250000
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>"; Key: Ratan Value: 200000
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>"; PHP Multidimensional Array
?>
PHP multidimensional array is also known as array of
arrays. It allows you to store tabular data in an array. PHP
Output:
multidimensional array can be represented in the form of
matrix which is represented by row * column.
Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000 Definition
31
PHP Multidimensional Array Example Output:
1 sonoo 400000
Let's see a simple example of PHP multidimensional array to
display following tabular data. In this example, we are 2 john 500000
displaying 3 rows and 3 columns. 3 rahul 300000
2 john 500000
1) PHP array() function
3 rahul 300000
PHP array() function creates and returns an array. It allows
you to create indexed, associative and multidimensional
arrays.
File: multiarray.php
Syntax
<?php
$emp = array
( array array ([ mixed $... ] )
array(1,"sonoo",400000),
array(2,"john",500000), Example
array(3,"rahul",300000)
);
<?php
for ($row = 0; $row < 3; $row++) { $season=array("summer","winter","spring","autumn");
for ($col = 0; $col < 3; $col++) { echo "Season are: $season[0], $season[1], $season[2] and
echo $emp[$row][$col]." ";
} $season[3]";
echo "<br/>"; ?>
}
?> Output:
32
2) PHP array_change_key_case() function Output:
PHP array_change_key_case() function changes the case of Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] =>
all key of an array. 200000 )
Example
array array_chunk ( array $array , int $size [, bool $preser
ve_keys = false ] )
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000", Example
"Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_UPPER)); <?php
?> $salary=array("Sonoo"=>"550000","Vimal"=>"250000",
"Ratan"=>"200000");
Output:
print_r(array_chunk($salary,2));
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] ?>
=> 200000 )
Output:
Example
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
<?php
[1] => Array ( [0] => 200000 )
$salary=array("Sonoo"=>"550000","Vimal"=>"250000", )
"Ratan"=>"200000");
print_r(array_change_key_case($salary,CASE_LOWER));
?>
33
4) PHP count() function <?php
$season=array("summer","winter","spring","autumn");
PHP count() function counts all elements in an array.
sort($season);
Syntax foreach( $season as $s )
{
int count ( mixed $array_or_countable [, int $mode = COUN echo "$s<br />";
T_NORMAL ] ) }
?>
Example
Output:
<?php
autumn
$season=array("summer","winter","spring","autumn"); spring
echo count($season); summer
?> winter
34
{ Output:
Syntax <?php
$name1=array("sonoo","john","vivek","smith");
mixed array_search ( mixed $needle , array $haystack [, b $name2=array("umesh","sonoo","kartik","smith");
ool $strict = false ] ) $name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
Example
{
echo "$n<br />";
<?php
}
$season=array("summer","winter","spring","autumn");
?>
$key=array_search("spring",$season);
echo $key; Output:
?>
sonoo
smith
35
PHP String $str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3";
A PHP string is a sequence of characters i.e. used to store ?>
and manipulate text. There are 2 ways to specify string in
PHP.
Output:
o single quoted Hello text multiple line text within single quoted string
o double quoted Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string
<?php
trying variable $num1
$str1='Hello text trying backslash n and backslash t inside single quoted
multiple line string \n \t
text within single quoted string'; Using single quote 'my quote' and \backslash
36
Double Quoted PHP String <?php
$str1="Hello text
In PHP, we can specify string through enclosing text within
multiple line
double quote also. But escape sequences and variables will
be interpreted using double quote PHP strings. text within double quoted string";
$str2="Using double \"quote\" with backslash inside double
<?php quoted string";
$str="Hello text within double quote"; $str3="Using escape sequences \n in double quoted string";
echo $str;
?> echo "$str1 <br/> $str2 <br/> $str3";
?>
Output:
Output:
Hello text within double quote
Hello text multiple line text within double quoted string
Now, you can't use double quote directly inside double Using double "quote" with backslash inside double quoted
quoted string. string
Using escape sequences in double quoted string
<?php
In double quoted strings, variable will be interpreted.
$str1="Using double "quote" directly inside double quoted s
tring";
<?php
echo $str1;
$num1=10;
?>
echo "Number is: $num1";
?>
Output:
37
PHP String Functions string strtoupper ( string $string )
38
Output: string ucwords ( string $str )
My name is KHAN
Example
Output:
string lcfirst ( string $str )
My Name Is Sonoo Jaiswal
Example
6) PHP strrev() function
<?php
$str="MY name IS KHAN"; The strrev() function returns reversed string.
$str=lcfirst($str);
Syntax
echo $str;
?>
string strrev ( string $string )
Output:
Example
mY name IS KHAN
<?php
5) PHP ucwords() function $str="my name is Sonoo jaiswal";
$str=strrev($str);
The ucwords() function returns string converting first echo $str;
character of each word into uppercase.
?>
Syntax
39
Output: The abs() function returns absolute value of given number.
It returns an integer value but if you pass floating point
lawsiaj oonoS si eman ym value, it returns a float value.
Syntax
7) PHP strlen() function
number abs ( mixed $number )
The strlen() function returns length of the string. Example
Syntax <?php
echo (abs(-7)."<br/>"); // 7 (integer)
int strlen ( string $string ) echo (abs(7)."<br/>"); //7 (integer)
echo (abs(-7.2)."<br/>"); //7.2 (float/double)
Example ?>
<?php Output:
$str="my name is Sonoo jaiswal";
7
$str=strlen($str); 7
echo $str; 7.2
?>
PHP Math: ceil() function
Output:
The ceil() function rounds fractions up.
24
Syntax
PHP Math
float ceil ( float $value )
PHP provides many predefined math constants and Example
functions that can be used to perform mathematical
<?php
operations.
echo (ceil(3.3)."<br/>");// 4
PHP Math: abs() function echo (ceil(7.333)."<br/>");// 8
echo (ceil(-4.8)."<br/>");// -4
?>
40
Output: <?php
echo (sqrt(16)."<br/>");// 4
4
8 echo (sqrt(25)."<br/>");// 5
-4 echo (sqrt(7)."<br/>");// 2.6457513110646
?>
PHP Math: floor() function
Output:
The floor() function rounds fractions down.
4
Syntax 5
float floor ( float $value ) 2.6457513110646
Example
PHP Math: decbin() function
<?php
echo (floor(3.3)."<br/>");// 3 The decbin() function converts decimal number into binary.
echo (floor(7.333)."<br/>");// 7 It returns binary number as a string.
echo (floor(-4.8)."<br/>");// -5
Syntax
?>
string decbin ( int $number )
Output: Example
<?php
3
echo (decbin(2)."<br/>");// 10
7
-5 echo (decbin(10)."<br/>");// 1010
echo (decbin(22)."<br/>");// 10110
PHP Math: sqrt() function ?>
Syntax 10
float sqrt ( float $arg ) 1010
10110
Example
41
PHP Math: dechex() function echo (decoct(22)."<br/>");// 26
?>
The dechex() function converts decimal number into
hexadecimal. It returns hexadecimal representation of given
Output:
number as a string.
2
Syntax 12
string dechex ( int $number ) 26
Example
PHP Math: base_convert() function
<?php
echo (dechex(2)."<br/>");// 2 The base_convert() function allows you to convert any base
echo (dechex(10)."<br/>");// a number to any base number. For example, you can convert
echo (dechex(22)."<br/>");// 16 hexadecimal number to binary, hexadecimal to octal, binary
to octal, octal to hexadecimal, binary to decimal etc.
?>
Syntax
Output:
string base_convert ( string $number , int $frombase , int $
2 tobase )
a
Example
16
<?php
PHP Math: decoct() function $n1=10;
echo (base_convert($n1,10,2)."<br/>");// 1010
The decoct() function converts decimal number into octal. It ?>
returns octal representation of given number as a string.
Output:
Syntax
string decoct ( int $number ) 1010
Example
PHP Math: bindec() function
<?php
echo (decoct(2)."<br/>");// 2 The bindec() function converts binary number into decimal.
echo (decoct(10)."<br/>");// 12
42
Syntax File: form1.html
number bindec ( string $binary_string ) <form action="welcome.php" method="get">
Example Name: <input type="text" name="name"/>
43
<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 $n
ame variable
$password=$_POST["password"];//receiving password field
value in $password variable
Output: 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
44
File: menu.html
<a href="http://www.javatpoint.com/java-
tutorial">Java</a> |
<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/html-
<a href="http://www.javatpoint.com/php-
tutorial">HTML</a>
tutorial">PHP</a> | File: require1.php
<a href="http://www.javatpoint.com/java-
tutorial">Java</a> | <?php require("menu.html"); ?>
<a href="http://www.javatpoint.com/html- <h1>This is Main Page</h1>
tutorial">HTML</a>
File: include1.php Output:
45
2. setcookie("CookieName", "CookieValue", time()+1*60*60);
//using expiry in 1 hour(1*60*60 seconds or 3600 seconds)
PHP $_COOKIE
Note: PHP Cookie must be used before <html> tag. $value=$_COOKIE["CookieName"];//returns cookie value
46
Output: PHP session creates unique user id for each browser to
recognize the user and avoid conflict between multiple
Sorry, cookie is not found! browsers.
Firstly cookie is not set. But, if you refresh the page, you
will see cookie is set now.
Output:
47
PHP $_SESSION File: session2.php
48
PHP Destroying Session Mode Description
r Opens file in read-only mode. It places the file pointer at
PHP session_destroy() function is used to destroy all session the beginning of the file.
variables completely. r+ Opens file in read-write mode. It places the file pointer at
the beginning of the file.
File: session3.php w Opens file in write-only mode. It places the file pointer to
<?php the beginning of the file and truncates the file to zero
session_start(); length. If file is not found, it creates a new file.
session_destroy(); w+ Opens file in read-write mode. It places the file pointer to
?> the beginning of the file and truncates the file to zero
length. If file is not found, it creates a new file.
a Opens file in write-only mode. It places the file pointer to
PHP File Handling the end of the file. If file is not found, it creates a new file.
a+ Opens file in read-write mode. It places the file pointer to
PHP File System allows us to create file, read file line by the end of the file. If file is not found, it creates a new file.
line, read file character by character, write file, append file, x Creates and opens file in write-only mode. It places the
delete file and close file. file pointer at the beginning of the file. If file is found,
fopen() function returns FALSE.
PHP Open File x+ It is same as x but it creates and opens file in read-
write mode.
PHP fopen() function is used to open file or URL and returns
c Opens file in write-only mode. If the file does not exist, it
resource. The fopen() function accepts two arguments:
$filename and $mode. The $filename represents the file to is created. If it exists, it is neither truncated (as opposed
be opended and $mode represents the file mode for to 'w'), nor the call to this function fails (as is the case
example read-only, read-write, write-only etc. with 'x'). The file pointer is positioned on the beginning of
the file
Syntax c+ It is same as c but it opens file in read-write mode.
resource fopen ( string $filename , string $mode [, bool PHP Open File Example
$use_include_path = false [, resource $context ]] )
<?php
PHP Open File Mode: $handle = fopen("c:\\folder\\file.txt", "r");
?>
49
PHP Read File
$contents = fread($fp, filesize($filename));//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. echo "<pre>$contents</pre>";//printing data of file
fclose($fp);//close file
The available PHP file read functions are given below.
?>
o fread()
Output
o fgets()
this is first line
o fgetc()
this is another line
this is third line
PHP Read File - fread()
PHP Read File - fgets()
The PHP fread() function is used to read data of the file. It
requires two arguments: file resource and file size.
The PHP fgets() function is used to read single line from the
file.
Syntax
Syntax
string fread (resource $handle , int $length )
string fgets ( resource $handle [, int $length ] )
$handle represents file pointer that is created by fopen()
function.
Example
$length represents length of byte to be read.
<?php
Example: $fp = fopen("c:\\file1.txt", "r");//open file in read mode
echo fgets($fp);
<?php fclose($fp);
$filename = "c:\\file1.txt";
?>
$fp = fopen($filename, "r");//open file in read mode
50
Output PHP Write File
this is first line PHP fwrite() and fputs() functions are used to write data
into file. To write data into file, you need to use w, r+, w+,
PHP Read File - fgetc() x, x+, c or c+ mode.
The PHP fgetc() function is used to read single character PHP Write File - fwrite()
from the file. To get all data using fgetc() function, use
!feof() function inside the while loop. The PHP fwrite() function is used to write content of the
string into file.
Syntax
Syntax
<?php
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
$fp = fopen('data.txt', 'w');//opens file in write-only mode
while(!feof($fp)) {
fwrite($fp, 'welcome ');
echo fgetc($fp);
fwrite($fp, 'to php file write');
}
fclose($fp);
fclose($fp);
?>
echo "File written successfully";
Output ?>
this is first line this is another line this is third line Output: data.txt
51
PHP Overwriting File PHP Append to File - fwrite()
If you run the above code again, it will erase the previous The PHP fwrite() function is used to write and append data
data of the file and writes the new data. Let's see the code into file.
that writes only new data into data.txt file.
Example
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode <?php
?>
echo "File appended successfully";
Output: data.txt ?>
hello Output:
welcome to php file write PHP unlink() generates E_WARNING level error if file is not
deleted. It returns TRUE if file is deleted successfully
otherwise FALSE.
52
Syntax PHP $_FILES
bool unlink ( string $filename [, resource $context ] ) The PHP global $_FILES contains all the information of file.
By the help of $_FILES global, we can get file name, file
type, file size, temp file name and errors associated with
$filename represents the name of the file to be deleted.
file.
PHP Delete File Example Here, we are assuming that file name is filename.
<?php $_FILES['filename']['name']
$status=unlink('data.txt');
returns file name.
if($status){
echo "File deleted successfully"; $_FILES['filename']['type']
}else{
returns MIME type of the file.
echo "Sorry!";
}
$_FILES['filename']['size']
?>
returns size of the file (in bytes).
Output
$_FILES['filename']['tmp_name']
File deleted successfully
returns temporary file name of the file which was stored on
PHP File Upload the server.
PHP allows you to upload single and multiple files through $_FILES['filename']['error']
few lines of code only.
returns error code associated with this file.
PHP file upload features allows you to upload binary and
text files both. Moreover, you can have the full control over
the file to be uploaded through PHP authentication and file
operation functions.
53
move_uploaded_file() function if(move_uploaded_file($_FILES['fileToUpload']['tmp_name']
, $target_path)) {
The move_uploaded_file() function moves the uploaded file
to a new location. The move_uploaded_file() function echo "File uploaded successfully!";
checks internally if the file is uploaded thorough the POST } else{
request. It moves the file if it is uploaded through the POST
request. echo "Sorry, file not uploaded, please try again!";
}
Syntax ?>
54
message Defines the message to be sent. Each line
should be separated with a line feed-LF
(\n). Lines should not exceed 70 characters. Sending HTML Formatted Emails
Optional — The following parameters are optional
headers This is typically used to add extra headers When you send a text message using PHP, all the content
such as "From", "Cc", "Bcc". The additional will be treated as simple text. We're going to improve that
headers should be separated with a carriage output, and make the email into a HTML-formatted email.
return plus a line feed-CRLF (\r\n). To send an HTML email, the process will be the same.
parameters Used to pass additional parameters. However, this time we need to provide additional headers as
well as an HTML formatted message.
Sending Plain Text Emails
The simplest way to send an email with PHP is to send a <?php
text email. In the example below we first declare the $to = 'maryjane@email.com';
variables — recipient's email address, subject line and $subject = 'Marriage Proposal';
message body — then we pass these variables to $from = 'peterparker@email.com';
the mail() function to send the email.
// To send HTML mail, the Content-type header must be set
<?php
$headers = 'MIME-Version: 1.0' . "\r\n";
$to = 'maryjane@email.com';
$headers .= 'Content-type: text/html; charset=iso-8859-1'
$subject = 'Marriage Proposal';
. "\r\n";
$message = 'Hi Jane, will you marry me?';
$from = 'peterparker@email.com';
// Create email headers
$headers .= 'From: '.$user_email."\r\n".
// Sending email
'Reply-To: '.$user_email."\r\n" .
if(mail($to, $subject, $message)){
'X-Mailer: PHP/' . phpversion();
echo 'Your mail has been sent successfully.';
} else{
// Compose a simple HTML email message
echo 'Unable to send email. Please try again.';
$message = '<html><body>';
}
$message .= '<h1 style="color:#f40;">Hi Jane!</h1>';
?>
$message .= '<p style="color:#080;font-size:18px;">Will
you marry me?</p>';
$message .= '</body></html>';
// Sending email
55
if(mail($to, $subject, $message, $headers)){ Function Description
echo 'Your mail has been sent successfully.';
} else{ date_diff() Returns the difference between
echo 'Unable to send email. Please try again.'; two dates
} date_format() Returns a date formatted
?> according to a specified format
date_get_last_errors() Returns the warnings and
errors found while parsing a
date/time string
PHP Date and Time Functions
date_interval_create_from Sets up a DateInterval from
The following date and time functions are the part of the _date_string() the relative parts of the string
PHP core so you can use these functions within your script
without any further installation. date_interval_format() Formats the interval
date_isodate_set() Set a date according to the ISO
Function Description 8601 standard
checkdate() Validates a Gregorian date date_modify() Modifies the timestamp
date_add() Adds an amount of days, date_offset_get() Returns the timezone offset
months, years, hours, minutes
and seconds to a date date_parse_from_format() Returns an associative array
with detailed info about given
date_create_from_format( Returns a new DateTime object date formatted according to the
) formatted according to the specified format
specified format
date_parse() Returns associative array with
date_create() Returns new DateTime object detailed info about a specified
date
date_date_set() Sets a new date
date_sub() Subtracts an amount of days,
date_default_timezone_ge Returns the default timezone months, years, hours, minutes
t() used by all date/time functions and seconds from a date
in a script
date_sun_info() Returns an array with
date_default_timezone_se Sets the default timezone used information about
t() by all date/time functions in a sunset/sunrise and twilight
script begin/end for a specified day
and location
56
57