Sie sind auf Seite 1von 180

PHP Tutorial

PHP tutorial for beginners and professionals provides deep knowledge of PHP scripting
language. Our PHP tutorial will help you to learn PHP scripting language easily. This PHP
tutorial covers all the topics of PHP such as introduction, control statements, functions, array,
string, file handling, form handling, regular expression, date and time, object-oriented
programming in PHP, math, PHP mysql, PHP with ajax, PHP with jquery and PHP with XML.

What is PHP
o PHP stands for HyperText Preprocessor.

o PHP is 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 language e.g. asp and jsp.

PHP Example
In this tutorial, you will get a lot of PHP examples to understand the topic well. The PHP file
must be save with .php extension. Let's see a simple PHP example.

File: hello.php
1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
5. echo "<h2>Hello by PHP</h2>";
6. ?>
7. </body>
8. </html>

Output:

Hello by PHP
Web Development
PHP is widely used in web development now a days. Dynamic websites can be easily developed
by PHP. But you must have the basic the knowledge of following technologies for web
development as well.
o HTML

o CSS

o JavaScript

o AJAX

o XML and JSON

o JQuery

next prev

What is PHP
PHP is a open source, interpreted and object-oriented scripting language i.e. executed at
server side. It is used to develop web applications (an application i.e. executed at server
side and generates dynamic page).

What is PHP
o PHP is a server side scripting language.

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.

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

o Open Source Software: PHP source code is free available on the web, you can
developed all the version of PHP according to your requirement without paying
any cost.

o Platform Independent: PHP are available for WINDOWS, MAC, LINUX & UNIX
operating system. A PHP application developed in one OS can be easily executed
in other OS also.
o Compatibility: PHP is compatible with almost all local servers used today like
Apache, IIS etc.

o Embedded: PHP code can be easily embedded within HTML tags and script.

Install PHP
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It is
available for all operating systems. There are many AMP options available in the market that
are given below:

o WAMP for Windows

o LAMP for Linux

o MAMP for Mac

o SAMP for Solaris

o FAMP for FreeBSD

o XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other
components too such as FileZilla, OpenSSL, Webalizer, OpenSSL, Mercury Mail etc.

If you are on Windows and don't want Perl and other features of XAMPP, you should go for
WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh.

Download and Install WAMP Server


Click me to download WAMP server

Download and Install LAMP Server


Click me to download LAMP server

Download and Install MAMP Server


Click me to download MAMP server

Download and Install XAMPP Server

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

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: Loosely typed language


PHP is a loosely typed language, it means PHP automatically converts the variable to its
correct data type.

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.

Now we have printed the values as $name, ${$name}, $Cat, ${${$name}} and $Dog.

PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the script.
PHP constants can be defined by 2 ways:

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, na
returned.

__DIR__ Represents full directory path of the file. Equivalent to dirname(__file__). It doe
slash unless it is a root directory. It also resolves symbolic link.

__FUNCTION__ Represents the function name where it is used. If it is used outside of any functio
blank.

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

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

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

__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

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

clone new clone and new non-


associative

[ array() left

** arithmetic right

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


(bool) @

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

PHP If-else Statement


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

Syntax
1. if(condition){
2. //code to be executed if true
3. }else{
4. //code to be executed if false
5. }

Flowchart
Example

1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
8. ?>

Output:

12 is even number
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works
like PHP if-else-if statement.

Syntax
1. switch(expression){
2. case value1:
3. //code to be executed
4. break;
5. case value2:
6. //code to be executed
7. break;
8. ......
9. default:
10. code to be executed if all cases are not matched;
11. }

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

1. while(condition):
2. //code to be executed
3.
4. endwhile;

PHP While Loop Flowchart


PHP While Loop Example

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

Output:

1
2
3
4
5
6
7
8
9
10

Alternative Example

1. <?php
2. $n=1;
3. while($n<=10):
4. echo "$n<br/>";
5. $n++;
6. endwhile;
7. ?>

Output:

1
2
3
4
5
6
7
8
9
10

PHP Nested While Loop


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

In case of inner or nested while loop, nested while loop is executed fully for one outer while
loop. If outer while loop is to be executed for 3 times and nested while loop for 3 times, nested
while loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and
3 times for 3rd outer loop).

Example

1. <?php
2. $i=1;
3. while($i<=3){
4. $j=1;
5. while($j<=3){
6. echo "$i $j<br/>";
7. $j++;
8. }
9. $i++;
10. }
11. ?>

Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

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
1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>

Output:

1
2
3
4
5
6
7
8
9
10

PHP Break
PHP break statement breaks the execution of current for, while, do-while, switch and for-each
loop. If you use break inside inner loop, it breaks the execution of inner loop only.

Syntax

1. jump statement;
2. break;

Flowchart
PHP Break: inside loop
Let's see a simple example to break the execution of for loop if value of i is equal to 5.

1. <?php
2. for($i=1;$i<=10;$i++){
3. echo "$i <br/>";
4. if($i==5){
5. break;
6. }
7. }
8. ?>

Output:

1
2
3
4
5

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.

1. <?php
2. $num=200;
3. switch($num){
4. case 100:
5. echo("number is equals to 100");
6. break;
7. case 200:
8. echo("number is equal to 200");
9. break;
10. case 50:
11. echo("number is equal to 300");
12. break;
13. default:
14. echo("number is not equal to 100, 200 or 500");
15. }
16. ?>

Output:

number is equal to 200

PHP Programs
PHP programs are frequently asked in the interview. These programs can be asked from
basics, control statements, array, string, oops, file handling etc. Let's see the list of top PHP
programs.

1) Sum of Digits
Write a PHP program to print sum of digits.

Input: 23

Output: 5

Input: 624

Output: 12

2) Even or odd number


Input: 23

Output: odd number

Input: 12

Output: even number

3) Prime number
Write a PHP program to check prime number.

Input: 17

Output: not prime number


Input: 57

Output: prime number

4) Table of number
Write a PHP program to print table of a number.

Input: 2

Output: 2 4 6 8 10 12 14 16 18 20

Input: 5

Output: 5 10 15 20 25 30 35 40 45 50

5) Factorial
Write a PHP program to print factorial of a number.

Input: 5

Output: 120

Input: 6

Output: 720

6) Armstrong number
Write a PHP program to check armstrong number.

Input: 371

Output: armstrong

Input: 342

Output: not armstrong


7) Palindrome number
Write a PHP program to check palindrome number.

Input: 121

Output: not palindrome number

Input: 113

Output: palindrome number

8) Fibonacci Series
Write a PHP program to print fibonacci series without using recursion and using recursion.

Input: 10

Output: 0 1 1 2 3 5 8 13 21 34

9) Reverse Number
Write a PHP program to reverse given number.

Input: 234

Output: 432

10) Reverse String


Write a PHP program to reverse given string.

Input: amit

Output: tima

11) Swap two numbers


Write a PHP program to swap two numbers with and without using third variable.
Input: a=5 b=10

Output: a=10 b=5

12) Adding Two Numbers


Write a PHP program to add two numbers.

First Input: 10

Second Input: 20

Output: 30

13) Subtracting Two Numbers


Write a PHP program to subtract two numbers.

First Input: 50

Second Input: 10

Output: 40

14) Area of Triangle


Write a PHP program to find area of triangle.

Base Input: 10

Height Input: 15

Output: 75

15) Area of rectangle


Write a PHP program to find the area of rectangle.

Length Input: 10
Width Input: 20

Output: 200

16) Leap Year


Write a PHP program to find if the given year is leap year or not.

Input: 2000

Output: Leap Year

Input: 2001

Output: Not Leap Year

17) Alphabet Triangle using PHP method


Write a PHP program to print alphabet triangle.

Output:

A
ABA
ABCBA
ABCDCBA
ABCDEDCBA

18) Alphabet Triangle Pattern


Write a PHP program to print alphabet triangle.

Output:

A
ABA
ABCBA
ABCDCBA
ABCDEDCBA

19) Number Triangle


Write a PHP program to print number triangle.

Output:
enter the range= 6
1
121
12321
1234321
123454321
12345654321

20) Star Triangle


Write a PHP programs to print star triangle.

Output:

Output:

Output:
Output:

Output:

Sum of Digits
To find sum of digits of a number just add all the digits.

For example,

1. 14597 = 1 + 4 + 5 + 9 + 7
2. 14597 = 26

Logic:

o Take the number.

o Divide the number by 10.

o Add the remainder to a variable.

o Repeat the process until remainder is 0.

Example:

Given program shows the sum of digits of 14597.

1. <?php
2. $num = 14597;
3. $sum=0; $rem=0;
4. for ($i =0; $i<=strlen($num);$i++)
5. {
6. $rem=$num%10;
7. $sum = $sum + $rem;
8. $num=$num/10;
9. }
10. echo "Sum of digits 14597 is $sum";
11. ?>

Output:

Even Odd Program


Even numbers are those which are divisible by 2. Numbers like 2,4,6,8,10, etc are even.

Odd numbers are those which are not divisible by 2. Numbers Like 1, 3, 5, 7, 9, 11, etc are
odd.

Logic:

o Take a number.

o Divide it by 2.

o If the remainder is 0, print number is even.

Even Odd Program in PHP


A program to check 1233456 is odd or even is shown.

Example:

1. <?php
2. $number=1233456;
3. if($number%2==0)
4. {
5. echo "$number is Even Number";
6. }
7. else
8. {
9. echo "$number is Odd Number";
10. }
11. ?>

Output:
Even Odd Program using Form in PHP
By inserting value in a form we can check that inserted value is even or odd.

Example:

1. <html>
2. <body>
3. <form method="post">
4. Enter a number:
5. <input type="number" name="number">
6. <input type="submit" value="Submit">
7. </form>
8. </body>
9. </html>
10. <?php
11. if($_POST){
12. $number = $_POST['number'];
13. //divide entered number by 2
14. //if the reminder is 0 then the number is even otherwise the number is odd
15. if(($number % 2) == 0){
16. echo "$number is an Even number";
17. }else{
18. echo "$number is Odd number";
19. }
20. }
21. ?>

Output:

On entering the number 23456, following output appears.

Prime Number
A number which is only divisible by 1 and itself is called prime number. Numbers 2, 3, 5, 7,
11, 13, 17, etc. are prime numbers.

o 2 is the only even prime number.

o It is a natural number greater than 1 and so 0 and 1 are not prime numbers.
Prime number in PHP
Example:

Here is the Program to list the first 15 prime numbers.

1. <?php
2. $count = 0;
3. $num = 2;
4. while ($count < 15 )
5. {
6. $div_count=0;
7. for ( $i=1; $i<=$num; $i++)
8. {
9. if (($num%$i)==0)
10. {
11. $div_count++;
12. }
13. }
14. if ($div_count<3)
15. {
16. echo $num." , ";
17. $count=$count+1;
18. }
19. $num=$num+1;
20. }
21. ?>

Output:
Prime Number using Form in PHP
Example:

We'll show a form, which will check whether a number is prime or not.

1. <form method="post">
2. Enter a Number: <input type="text" name="input"><br><br>
3. <input type="submit" name="submit" value="Submit">
4. </form>
5. <?php
6. if($_POST)
7. {
8. $input=$_POST['input'];
9. for ($i = 2; $i <= $input-1; $i++) {
10. if ($input % $i == 0) {
11. $value= True;
12. }
13. }
14. if (isset($value) && $value) {
15. echo 'The Number '. $input . ' is not prime';
16. } else {
17. echo 'The Number '. $input . ' is prime';
18. }
19. }
20. ?>

Output:

On entering number 12, we get the following output. It states that 12 is not a prime number.
On entering number 97, we get the following output. It states that 97 is a prime number.

On entering the number 285965, following output appears.


Table of Number
A table of a number can be printed using a loop in program.

Logic:

o Define the number.

o Run for loop.

o Multiply the number with for loop output.

Example:

We'll print the table of 7.

1. <?php
2. define('a', 7);
3. for($i=1; $i<=10; $i++)
4. {
5. echo $i*a;
6. echo '<br>';
7. }
8. ?>

Output:
Factorial Program
The factorial of a number n is defined by the product of all the digits from 1 to n (including 1
and n).

For example,

1. 4! = 4*3*2*1 = 24
2. 6! = 6*5*4*3*2*1 = 720

Note:

o It is denoted by n! and is calculated only for positive integers.

o Factorial of 0 is always 1.

The simplest way to find the factorial of a number is by using a loop.

There are two ways to find factorial in PHP:

o Using loop

o Using recursive method

Logic:
o Take a number.
o Take the descending positive integers.

o Multiply them.

Factorial in PHP
Factorial of 4 using for loop is shown below.

Example:

1. <?php
2. $num = 4;
3. $factorial = 1;
4. for ($x=$num; $x>=1; $x--)
5. {
6. $factorial = $factorial * $x;
7. }
8. echo "Factorial of $num is $factorial";
9. ?>

Output:

Factorial using Form in PHP


Below program shows a form through which you can calculate factorial of any number.

Example:

1. <html>
2. <head>
3. <title>Factorial Program using loop in PHP</title>
4. </head>
5. <body>
6. <form method="post">
7. Enter the Number:<br>
8. <input type="number" name="number" id="number">
9. <input type="submit" name="submit" value="Submit" />
10. </form>
11. <?php
12. if($_POST){
13. $fact = 1;
14. //getting value from input text box 'number'
15. $number = $_POST['number'];
16. echo "Factorial of $number:<br><br>";
17. //start loop
18. for ($i = 1; $i <= $number; $i++){
19. $fact = $fact * $i;
20. }
21. echo $fact . "<br>";
22. }
23. ?>
24. </body>
25. </html>

Output:
Factorial using Recursion in PHP
Factorial of 6 using recursion method is shown.

Example:

1. <?php
2. function fact ($n)
3. {
4. if($n <= 1)
5. {
6. return 1;
7. }
8. else
9. {
10. return $n * fact($n - 1);
11. }
12. }
13.
14. echo "Factorial of 6 is " .fact(6);
15. ?>

Output:

Armstrong Number
An Armstrong number is the one whose value is equal to the sum of the cubes of its digits.

0, 1, 153, 371, 407, 471, etc are Armstrong numbers.

For example,

1. 407 = (4*4*4) + (0*0*0) + (7*7*7)


2. = 64 + 0 + 343
3. 407 = 407
Logic:

o Take the number.

o Store it in a variable.

o Take a variable for sum.

o Divide the number with 10 until quotient is 0.

o Cube the remainder.

o Compare sum variable and number variable.

Armstrong number in PHP


Below program checks whether 407 is Armstrong or not.

Example:

1. <?php
2. $num=407;
3. $total=0;
4. $x=$num;
5. while($x!=0)
6. {
7. $rem=$x%10;
8. $total=$total+$rem*$rem*$rem;
9. $x=$x/10;
10. }
11. if($num==$total)
12. {
13. echo "Yes it is an Armstrong number";
14. }
15. else
16. {
17. echo "No it is not an armstrong number";
18. }
19. ?>

Output:
Look at the above snapshot, the output displays that 407 is an Armstrong number.

Armstrong number using Form in PHP


A number is Armstrong or can also be checked using a form.

Example:

1. <html>
2. <body>
3. <form method="post">
4. Enter the Number:
5. <input type="number" name="number">
6. <input type="submit" value="Submit">
7. </form>
8. </body>
9. </html>
10. <?php
11. if($_POST)
12. {
13. //get the number entered
14. $number = $_POST['number'];
15. //store entered number in a variable
16. $a = $number;
17. $sum = 0;
18. //run loop till the quotient is 0
19. while( $a != 0 )
20. {
21. $rem = $a % 10; //find reminder
22. $sum = $sum + ( $rem * $rem * $rem ); //cube the reminder and add it to the sum var
iable till the loop ends
23. $a = $a / 10; //find quotient. if 0 then loop again
24. }
25. //if the entered number and $sum value matches then it is an armstrong number
26. if( $number == $sum )
27. {
28. echo "Yes $number an Armstrong Number";
29. }else
30. {
31. echo "$number is not an Armstrong Number";
32. }
33. }
34. ?>

Output:

On entering the number 371, we got the following output.

On entering the number 9999, we got the following output.


Palindrome Number
A palindrome number is a number which remains same when its digits are reversed.

For example, number 24142 is a palindrome number. On reversing it we?ll get the same
number.

Logic:

o Take a number.

o Reverse the input number.

o Compare the two numbers.

o If equal, it means number is palindrome

Palindrome Number in PHP


Example:

1. <?php
2. function palindrome($n){
3. $number = $n;
4. $sum = 0;
5. while(floor($number)) {
6. $rem = $number % 10;
7. $sum = $sum * 10 + $rem;
8. $number = $number/10;
9. }
10. return $sum;
11. }
12. $input = 1235321;
13. $num = palindrome($input);
14. if($input==$num){
15. echo "$input is a Palindrome number";
16. } else {
17. echo "$input is not a Palindrome";
18. }
19. ?>

Output:

Palindrome Number using Form in PHP


Example:

We'll show the logic to check whether a number is palindrome or not.

1. <form method="post">
2. Enter a Number: <input type="text" name="num"/><br>
3. <button type="submit">Check</button>
4. </form>
5. <?php
6. if($_POST)
7. {
8. //get the value from form
9. $num = $_POST['num'];
10. //reversing the number
11. $reverse = strrev($num);
12.
13. //checking if the number and reverse is equal
14. if($num == $reverse){
15. echo "The number $num is Palindrome";
16. }else{
17. echo "The number $num is not a Palindrome";
18. }
19. }
20. ?>

Output:

On entering the number 23432, we get the following output.

On entering the number 12345, we get the following output.

Fibonacci
Series
Fibonacci series is the one in which you will get your next term by adding previous two
numbers.

For example,

1. 0 1 1 2 3 5 8 13 21 34
2. Here, 0 + 1 = 1
3. 1+1=2
4. 3+2=5

and so on.

Logic:
o Initializing first and second number as 0 and 1.

o Print first and second number.

o From next number, start your loop. So third number will be the sum of the first two
numbers.

Example:

We'll show an example to print the first 12 numbers of a Fibonacci series.

1. <?php
2. $num = 0;
3. $n1 = 0;
4. $n2 = 1;
5. echo "<h3>Fibonacci series for first 12 numbers: </h3>";
6. echo "\n";
7. echo $n1.' '.$n2.' ';
8. while ($num < 10 )
9. {
10. $n3 = $n2 + $n1;
11. echo $n3.' ';
12. $n1 = $n2;
13. $n2 = $n3;
14. $num = $num + 1;
15. ?>

Output:
Fibonacci series using Recursive function
Recursion is a phenomenon in which the recursion function calls itself until the base condition
is reached.

1. <?php
2. /* Print fiboancci series upto 12 elements. */
3. $num = 12;
4. echo "<h3>Fibonacci series using recursive function:</h3>";
5. echo "\n";
6. /* Recursive function for fibonacci series. */
7. function series($num){
8. if($num == 0){
9. return 0;
10. }else if( $num == 1){
11. return 1;
12. } else {
13. return (series($num-1) + series($num-2));
14. }
15. }
16. /* Call Function. */
17. for ($i = 0; $i < $num; $i++){
18. echo series($i);
19. echo "\n";
20. }

Output:
Reverse number
A number can be written in reverse order.

For example

12345 = 54321

Logic:

o Declare a variable to store reverse number and initialize it with 0.

o Multiply the reverse number by 10, add the remainder which comes after dividing the
number by 10.

Reversing Number in PHP


Example:

Below progrem shows digits reversal of 23456.

1. <?php
2. $num = 23456;
3. $revnum = 0;
4. while ($num > 1)
5. {
6. $rem = $num % 10;
7. $revnum = ($revnum * 10) + $rem;
8. $num = ($num / 10);
9. }
10. echo "Reverse number of 23456 is: $revnum";
11. ?>

Output:

Reversing Number With strrev () in PHP


Example:

Function strrev() can also be used to reverse the digits of 23456.

1. <?php
2. function reverse($number)
3. {
4. /* writes number into string. */
5. $num = (string) $number;
6. /* Reverse the string. */
7. $revstr = strrev($num);
8. /* writes string into int. */
9. $reverse = (int) $revstr;
10. return $reverse;
11. }
12. echo reverse(23456);
13. ?>

Output:/strong>
Reverse String
A string can be reversed either using strrev() function or simple PHP code.

For example, on reversing JAVATPOINT it will become TNIOPTAVAJ.

Logic:

o Assign the string to a variable.

o Calculate length of the string.

o Declare variable to hold reverse string.

o Run for loop.

o Concatenate string inside for loop.

o Display reversed string.

Reverse String using strrev() function


A reverse string program using strrev() function is shown.

Example:

1. <?php
2. $string = "JAVATPOINT";
3. echo "Reverse string of $string is " .strrev ( $string );
4. ?>

Output:
Reverse String Without using strrev() function
A reverse string program without using strrev() function is shown.

Example:

1. <?php
2. $string = "JAVATPOINT";
3. $length = strlen($string);
4. for ($i=($length-1) ; $i >= 0 ; $i--)
5. {
6. echo $string[$i];
7. }
8. ?>

Output:

Swapping two numbers


Two numbers can be swapped or interchanged. It means first number will become second
and second number will become first.

For example

1. a = 20, b = 30
2. After swapping,
3. a = 30, b = 20

There are two methods for swapping:

o By using third variable.

o Without using third variable.

Swapping Using Third Variable


Swap two numbers 45 and 78 using a third variable.

Example:

1. <?php
2. $a = 45;
3. $b = 78;
4. // Swapping Logic
5. $third = $a;
6. $a = $b;
7. $b = $third;
8. echo "After swapping:<br><br>";
9. echo "a =".$a." b=".$b;
10. ?>

Output:

Swapping Without using Third Variable


Swap two numbers without using a third variable is done in two ways:

o Using arithmetic operation + and ?

o Using arithmetic operation * and /

Example for (+ and -):

1. <?php
2. $a=234;
3. $b=345;
4. //using arithmetic operation
5. $a=$a+$b;
6. $b=$a-$b;
7. $a=$a-$b;
8. echo "Value of a: $a</br>";
9. echo "Value of b: $b</br>";
10. ?>

Output:

Example for (* and /):

1. <?php
2. $a=234;
3. $b=345;
4. // using arithmetic operation
5. $a=$a*$b;
6. $b=$a/$b;
7. $a=$a/$b;
8. echo "Value of a: $a</br>";
9. echo "Value of b: $b</br>";
10. ?>
Output:

Adding Two Numbers


There are three methods to add two numbers:

o Adding in simple code in PHP

o Adding in form in PHP

o Adding without using arithmetic operator (+).

Adding in Simple Code


Addition of two numbers 15 and 30 is shown here.

Example:

1. <?php
2. $x=15;
3. $y=30;
4. $z=$x+$y;
5. echo "Sum: ",$z;
6. ?>

Output:
Adding in Form
Two numbers can be added by passing input value in the form.

Example:

1. <html>
2. <body>
3. <form method="post">
4. Enter First Number:
5. <input type="number" name="number1" /><br><br>
6. Enter Second Number:
7. <input type="number" name="number2" /><br><br>
8. <input type="submit" name="submit" value="Add">
9. </form>
10. <?php
11. if(isset($_POST['submit']))
12. {
13. $number1 = $_POST['number1'];
14. $number2 = $_POST['number2'];
15. $sum = $number1+$number2;
16. echo "The sum of $number1 and $number2 is: ".$sum;
17. }
18. ?>
19. </body>
20. </html>

Output:
Adding in Simple Code
Two numbers can be added by passing input value in the form but without using (+) operator.

1. <body>
2. <form>
3. Enter First Number:
4. <input type="number" name="number1" /><br><br>
5. Enter Second Number:
6. <input type="number" name="number2" /><br><br>
7. <input type="submit" name="submit" value="Add">
8. </form>
9. </body>
10. <?php
11. @$number1=$_GET['number1'];
12. @$number2=$_GET['number2'];
13. for ($i=1; $i<=$number2; $i++)
14. {
15. $number1++;
16. }
17. echo "Sum of $number1 and $number2 is=".$number2;
18. ?>
Output:

Subtracting Two Numbers


There are three methods to subtract two numbers:

o Subtraction in simple code in PHP

o Subtraction in form in PHP

o Subtraction without using arithmetic operator (+).

Subtraction in Simple Code


Subtraction of two numbers 30 and 15 is shown.

Example:

1. <?php
2. $x=30;
3. $y=15;
4. $z=$x-$y;
5. echo "Difference: ",$z;
6. ?>

Output:

Subtraction in Form
By inserting values in the form two numbers can be subtracted.

Example:
1. <html>
2. <body>
3. <form method="post">
4. Enter First Number:
5. <input type="number" name="number1" /><br><br>
6. Enter Second Number:
7. <input type="number" name="number2" /><br><br>
8. <input type="submit" name="submit" value="Subtract">
9. </form>
10. <?php
11. if(isset($_POST['submit']))
12. {
13. $number1 = $_POST['number1'];
14. $number2 = $_POST['number2'];
15. $sum = $number1-$number2;
16. echo "The difference of $number1 and $number2 is: ".$sum;
17. }
18. ?>
19. </body>
20. </html>

Output:
Subtraction in Form without (-) Operator
By inserting values in the form two numbers can be subtracted but without using (-) operator.

Example:

1. <body>
2. <form>
3. Enter First Number:
4. <input type="number" name="number1" /><br><br>
5. Enter Second Number:
6. <input type="number" name="number2" /><br><br>
7. <input type="submit" name="submit" value="Subtract">
8. </form>
9. </body>
10. <?php
11.
12. @$number1=$_GET['number1'];
13. @$number2=$_GET['number2'];
14. for ($i=1; $i<=$number2; $i++)
15. {
16. $number1--;
17. }
18. echo "Difference=".$number1;
19. ?>

Output:

Area of Triangle
Area of a triangle is calculated by the following Mathematical formula,

1. (base * height) / 2 = Area

Area of Triangle in PHP


Program to calculate area of triangle with base as 10 and height as 15 is shown.

Example:
1. <?php
2. $base = 10;
3. $height = 15;
4. echo "area with base $base and height $height= " . ($base * $height) / 2;
5. ?>

Output:

Area of Triangle with Form in PHP


Program to calculate area of triangle by inserting values in the form is shown.

Example:

1. <html>
2. <body>
3. <form method = "post">
4. Base: <input type="number" name="base">
5. <br><br>
6. Height: <input type="number" name="height"><br>
7. <input type = "submit" name = "submit" value="Calculate">
8. </form>
9. </body>
10. </html>
11. <?php
12. if(isset($_POST['submit']))
13. {
14. $base = $_POST['base'];
15. $height = $_POST['height'];
16. $area = ($base*$height) / 2;
17. echo "The area of a triangle with base as $base and height as $height is $area";
18. }
19. ?>

Output:

Area of a Rectangle
Area of a rectangle is calculated by the mathematical formula,

1. Length Breadth = Area

Logic:

o Take two variables.

o Multiply both of them.

Area of Rectangle in PHP


Program to calculate area of rectangle with length as 14 and width as 12 is shown.

Example:

1. <?php
2. $length = 14;
3. $width = 12;
4. echo "area of rectangle is $length * $width= " . ($length * $width) . "<br />";
5. ?>

Output:

Area of Rectangle with Form in PHP


Program to calculate area of rectangle by inserting values in the form is shown.

Example:

1. <html>
2. <body>
3. <form method = "post">
4. Width: <input type="number" name="width">
5. <br><br>
6. Length: <input type="number" name="length"> <br>
7. <input type = "submit" name = "submit" value="Calculate">
8. </form>
9. </body>
10. </html>
11. <?php
12. if(isset($_POST['submit']))
13. {
14. $width = $_POST['width'];
15. $length = $_POST['length'];
16. $area = $width*$length;
17. echo "The area of a rectangle with $width x $length is $area";
18. }
19. ?>

Output:
Leap Year
Program
A leap year is the one which has 366 days in a year. A leap year comes after every four years.
Hence a leap year is always a multiple of four.

For example, 2016, 2020, 2024, etc are leap years.

Leap Year Program


This program states whether a year is leap year or not from the specified range of years (1991
- 2016).

Example:

1. <?php
2. function isLeap($year)
3. {
4. return (date('L', mktime(0, 0, 0, 1, 1, $year))==1);
5. }
6. //For testing
7. for($year=1991; $year<2016; $year++)
8. {
9. If (isLeap($year))
10. {
11. echo "$year : LEAP YEAR<br />\n";
12. }
13. else
14. {
15. echo "$year : Not leap year<br />\n";
16. }
17. }
18. ?>

Output:
Leap Year Program in Form
This program states whether a year is leap year or not by inserting a year in the form.

Example:

1. <html>
2. <body>
3. <form method="post">
4. Enter the Year: <input type="text" name="year">
5. <input type="submit" name="submit" value="Submit">
6. </form>
7. </body>
8. </html>
9. <?php
10. if($_POST)
11. {
12. //get the year
13. $year = $_POST['year'];
14. //check if entered value is a number
15. if(!is_numeric($year))
16. {
17. echo "Strings not allowed, Input should be a number";
18. return;
19. }
20. //multiple conditions to check the leap year
21. if( (0 == $year % 4) and (0 != $year % 100) or (0 == $year % 400) )
22. {
23. echo "$year is a Leap Year";
24. }
25. else
26. {
27. echo "$year is not a Leap Year";
28. }
29. }
30. ?>

Output:

On entering year 2016, we get the following output.


On entering year 2019, we get the following output.

Alphabet
Triangle Method
There are three methods to print the alphabets in a triangle or in a pyramid form.

o range() with for loop

o chr() with for loop

o range() with foreach loop

Logic:

o Two for loops are used.

o First for loop set conditions to print 1 to 5 rows.

o Second for loop set conditions in decreasing order.

Using range() function


This range function stores values in an array from A to Z. here, we use two for loops.

Example:

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=5; $j>$i; $j--){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Using chr() function


Here the chr() function returns the value of the ASCII code. The ASCII value of A, B, C, D, E
is 65, 66, 67, 68, 69 respectively. Here, also we use two for loops.

Example:

1. <?php
2. for( $i=65; $i<=69; $i++){
3. for($j=5; $j>=$i-64; $j--){
4. echo chr($i);
5. }
6. echo "<br>";
7. }
8. ?>

Output:
Using range() function with foreach
In this methods we use foreach loop with range() function. The range() function contain values
in an array and returns it with $char variable. The for loop is used to print the output.

Example:

1. <?php
2. $k=1;
3. foreach(range('A','Z') as $char){
4. for($i=5; $i>=$k; $i--){
5. echo $char;
6. }
7. echo "<br>";
8. $k=$k+1;

Output:

Alphabet Triangle Pattern


Some different alphabet triangle patterns using range() function in PHP are shown below.

Pattern 1
1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=5; $j>$i; $j--){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Pattern 2

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=0; $j<=$i; $j++){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>

Output:
Pattern 3

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=0; $j<=$i; $j++){
5. echo $alpha[$j];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Pattern 4

1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=4; $j>=$i; $j--){
5. echo $alpha[$j];
6. }
7. echo "<br>";
8. }
9. ?>

Output:

Pattern 5

1. <?php
2. $alpha = range('A', 'Z');
3. for ($i=5; $i>=1; $i--) {
4. for($j=0; $j<=$i; $j++) {
5. echo '';
6. }
7. $j--;
8. for ($k=0; $k<=(5-$j); $k++) {
9. echo $alpha[$k];
10. }
11. echo "<br>\n";
12. }
13. ?>

Output:

Number Triangle
Number triangle in PHP can be printed using for and foreach loop. There are a lot of patterns
in number triangle. Some of them are show here.
Pattern1

1. <?php
2. $k=1;
3. for($i=0;$i<4;$i++){
4. for($j=0;$j<=$i;$j++){
5. echo $k." ";
6. $k++;
7. }
8. echo "<br>";
9. }
10. ?>

Output:

Pattern 2

1. <?php
2. $k=1;
3. for($i=0;$i<5;$i++){
4. for($j=0;$j<=$i;$j++){
5. if($j%2==0)
6. {
7. $k=0;
8. }
9. else
10. {
11. $k=1;
12. }
13. echo $k." ";
14. }
15. echo "<br>";
16. }
17. ?>

Output:

Pattern 3

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo $j;
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Pattern 4

1. <?php
2. for($i=0;$i>=5;$i++){
3. for($j=1;$j>=$i;$j++){
4. echo $i;
5. }
6. echo "<br>";
7. }
8. ?<

Output:

Pattern 5

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo "1";
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Pattern 6
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo "1";
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Pattern 7

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo $j;
5. }
6. echo "<br>";
7. }
8. ?>

Output:
Pattern 8

1. <?php
2. for($i=5;$i>=1;$i--){
3. for($j=$i;$j>=1;$j--){
4. echo $i."";
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Star Triangle
The star triangle in PHP is made using for and foreach loop. There are a lot of star patterns.
We'll show some of them here.

Pattern 1

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo "* ";
5. }
6. echo "<br>";
7. }
8. ?>

Output:
Pattern 2

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo "* ";
5. }
6. echo "<br>";
7. }
8. ?>

Output:

Pattern 3

1. <?php
2. for($i=0;$i<=5;$i++){
3. for($k=5;$k>=$i;$k--){
4. echo " ";
5. }
6. for($j=1;$j<=$i;$j++){
7. echo "* ";
8. }
9. echo "<br>";
10. }
11. for($i=4;$i>=1;$i--){
12. for($k=5;$k>=$i;$k--){
13. echo " ";
14. }
15. for($j=1;$j<=$i;$j++){
16. echo "* ";
17. }
18. echo "<br>";
19. }
20. ?>

Output:

Pattern 4

1. <?php
2. for($i=1; $i<=5; $i++){
3. for($j=1; $j<=$i; $j++){
4. echo ' * ';
5. }
6. echo '<br>';
7. }
8. for($i=5; $i>=1; $i--){
9. for($j=1; $j<=$i; $j++){
10. echo ' * ';
11. }
12. echo '<br>';
13. }
14. ?>

Output:

Pattern 5

1. <?php
2. for ($i=1; $i<=5; $i++)
3. {
4. for ($j=1; $j<=5; $j++)
5. {
6. echo '* ';
7. }
8. echo "</br>";
9. }
10. ?>

Output:
Pattern 6

1. <?php
2. for($i=5; $i>=1; $i--)
3. {
4. if($i%2 != 0)
5. {
6. for($j=5; $j>=$i; $j--)
7. {
8. echo "* ";
9. }
10. echo "<br>";
11. }
12. }
13. for($i=2; $i<=5; $i++)
14. {
15. if($i%2 != 0)
16. {
17. for($j=5; $j>=$i; $j--)
18. {
19. echo "* ";
20. }
21. echo "<br>";
22. }
23. }
24. ?>

Output:
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument
list and return value. There are thousands of built-in functions in PHP.

In PHP, we can define Conditional function, Function within Function and Recursive
function also.

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. }
Note: Function name must be start with letter and underscore only like other labels in PHP. It can't be
start with numbers or special symbols.

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().

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Parameter Addition and Subtraction Example</title>
5. </head>
6. <body>
7. <?php
8. //Adding two numbers
9. function add($x, $y) {
10. $sum = $x + $y;
11. echo "Sum of two numbers is = $sum <br><br>";
12. }
13. add(467, 943);
14.
15. //Subtracting two numbers
16. function sub($x, $y) {
17. $diff = $x - $y;
18. echo "Difference between two numbers is = $diff";
19. }
20. sub(943, 467);
21. ?>
22. </body>
23. </html>

Output:

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().

1. <?php
2. //add() function with two parameter
3. function add($x,$y)
4. {
5. $sum=$x+$y;
6. echo "Sum = $sum <br><br>";
7. }
8. //sub() function with two parameter
9. function sub($x,$y)
10. {
11. $sub=$x-$y;
12. echo "Diff = $sub <br><br>";
13. }
14. //call function, get two argument through input box and click on add or sub button
15. if(isset($_POST['add']))
16. {
17. //call add() function
18. add($_POST['first'],$_POST['second']);
19. }
20. if(isset($_POST['sub']))
21. {
22. //call add() function
23. sub($_POST['first'],$_POST['second']);
24. }
25. ?>
26. <form method="post">
27. Enter first number: <input type="number" name="first"/><br><br>
28. Enter second number: <input type="number" name="second"/><br><br>
29. <input type="submit" name="add" value="ADDITION"/>
30. <input type="submit" name="sub" value="SUBTRACTION"/>
31. </form>

Output:

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.

1. <?php
2. function adder($str2)
3. {
4. $str2 .= 'Call By Value';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>

Output:

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

1. <?php
2. function increment($i)
3. {
4. $i++;
5. }
6. $i = 10;
7. increment($i);
8. echo $i;
9. ?>

Output:

10

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.

1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'This is ';
7. adder($str);
8. echo $str;
9. ?>
Output:

This is Call By Reference


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

1. <?php
2. function increment(&$i)
3. {
4. $i++;
5. }
6. $i = 10;
7. increment($i);
8. echo $i;
9. ?>

Output:

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
Since PHP 5, you can use the concept of default argument value with call by reference also.

Example 2
1. <?php
2. function greeting($first="Sonoo",$last="Jaiswal"){
3. echo "Greeting: $first $last<br/>";
4. }
5. greeting();
6. greeting("Rahul");
7. greeting("Michael","Clark");
8. ?>

Output:

Greeting: Sonoo Jaiswal


Greeting: Rahul Jaiswal
Greeting: Michael Clark
Example 3
1. <?php
2. function add($n1=10,$n2=10){
3. $n3=$n1+$n2;
4. echo "Addition is: $n3<br/>";
5. }
6. add();
7. add(20);
8. add(40,40);
9. ?>

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.


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

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


1. <?php
2. function display($number) {
3. if($number<=5){
4. echo "$number <br/>";
5. display($number+1);
6. }
7. }
8.
9. display(1);
10. ?>

Output:

1
2
3
4
5
Example 2 : Factorial Number
1. <?php
2. function factorial($n)
3. {
4. if ($n < 0)
5. return -1; /*Wrong value*/
6. if ($n == 0)
7. return 1; /*Terminating condition*/
8. return ($n * factorial ($n -1));
9. }
10.
11. echo factorial(5);
12. ?>

Output:

120

PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.

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:

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

2nd way:

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

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

Output:

Season are: summer, winter, spring and autumn


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

Season are: summer, winter, spring and autumn


Click me for more details...

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:

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

2nd way:

1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";

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

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000
File: arrayassociative2.php
1. <?php
2. $salary["Sonoo"]="350000";
3. $salary["John"]="450000";
4. $salary["Kartik"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "John salary: ".$salary["John"]."<br/>";
7. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
8. ?>

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000

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

PHP Indexed Array Example


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

Output:

Size: Big, Medium and Short


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

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
1. <?php
2. $size=array("Big","Medium","Short");
3. foreach( $size as $s )
4. {
5. echo "Size is: $s<br />";
6. }
7. ?>

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.

1. <?php
2. $size=array("Big","Medium","Short");
3. echo count($size);
4. ?>

Output:
3

PHP Associative Array


PHP allows you to associate name/label with each array elements in PHP using => symbol.
Such way, you can easily remember the element because each element is represented by
label than an incremented number.

Definition
There are two ways to define associative array:

1st way:

1. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");

2nd way:

1. $salary["Sonoo"]="550000";
2. $salary["Vimal"]="250000";
3. $salary["Ratan"]="200000";

Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
5. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
6. ?>

Output:

Sonoo salary: 550000


Vimal salary: 250000
Ratan salary: 200000
File: arrayassociative2.php
1. <?php
2. $salary["Sonoo"]="550000";
3. $salary["Vimal"]="250000";
4. $salary["Ratan"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
7. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
8. ?>

Output:

Sonoo salary: 550000


Vimal salary: 250000
Ratan salary: 200000

Traversing PHP Associative Array


By the help of PHP for each loop, we can easily traverse the elements of PHP associative array.

1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. foreach($salary as $k => $v) {
4. echo "Key: ".$k." Value: ".$v."<br/>";
5. }
6. ?>

Output:

Key: Sonoo Value: 550000


Key: Vimal Value: 250000
Key: Ratan Value: 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

1. <?php
2. $emp = array
3. (
4. array(1,"sonoo",400000),
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
11. echo $emp[$row][$col]." ";
12. }
13. echo "<br/>";
14. }
15. ?>

Output:

1 sonoo 400000
2 john 500000
3 rahul 300000

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

1. array array ([ mixed $... ] )

Example

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

Output:

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

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

Example

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

3. print_r(array_change_key_case($salary,CASE_UPPER));
4. ?>

Output:

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

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

3. print_r(array_change_key_case($salary,CASE_LOWER));
4. ?>

Output:

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

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

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

Example

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

3. print_r(array_chunk($salary,2));
4. ?>

Output:

Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)

4) PHP count() function


PHP count() function counts all elements in an array.

Syntax

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

Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>

Output:

5) PHP sort() function


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

Syntax

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

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. sort($season);
4. foreach( $season as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>

Output:

autumn
spring
summer
winter

6) PHP array_reverse() function


PHP array_reverse() function returns an array containing elements in reversed order.

Syntax

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


Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>

Output:

autumn
spring
winter
summer

7) PHP array_search() function


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

Syntax

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

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>

Output:

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

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

Example

1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>

Output:

sonoo
smith

PHP String
A PHP string is a sequence of characters i.e. used to store and manipulate text. There are 4
ways to specify string in PHP.

o single quoted

o double quoted

o heredoc syntax

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


PHP provides various string functions to access and manipulate strings. A list of important
PHP string functions are given below.

1) PHP strtolower() function


The strtolower() function returns string in lowercase letter.

Syntax

1. string strtolower ( string $string )

Example

1. <?php
2. $str="My name is KHAN";
3. $str=strtolower($str);
4. echo $str;
5. ?>

Output:

my name is khan

2) PHP strtoupper() function


The strtoupper() function returns string in uppercase letter.

Syntax

1. string strtoupper ( string $string )

Example

1. <?php
2. $str="My name is KHAN";
3. $str=strtoupper($str);
4. echo $str;
5. ?>

Output:

MY NAME IS KHAN

3) PHP ucfirst() function


The ucfirst() function returns string converting first character into uppercase. It doesn't
change the case of other characters.

Syntax

1. string ucfirst ( string $str )

Example

1. <?php
2. $str="my name is KHAN";
3. $str=ucfirst($str);
4. echo $str;
5. ?>

Output:

My name is KHAN

4) PHP lcfirst() function


The lcfirst() function returns string converting first character into lowercase. It doesn't change
the case of other characters.

Syntax

1. string lcfirst ( string $str )

Example

1. <?php
2. $str="MY name IS KHAN";
3. $str=lcfirst($str);
4. echo $str;
5. ?>
Output:

mY name IS KHAN

5) PHP ucwords() function


The ucwords() function returns string converting first character of each word into uppercase.

Syntax

1. string ucwords ( string $str )

Example

1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=ucwords($str);
4. echo $str;
5. ?>

Output:

My Name Is Sonoo Jaiswal

6) PHP strrev() function


The strrev() function returns reversed string.

Syntax

1. string strrev ( string $string )

Example

1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strrev($str);
4. echo $str;
5. ?>

Output:

lawsiaj oonoS si eman ym


7) PHP strlen() function
The strlen() function returns length of the string.

Syntax

1. int strlen ( string $string )

Example

1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strlen($str);
4. echo $str;
5. ?>

Output:

24

PHP Math
PHP provides many predefined math constants and functions that can be used to perform
mathematical operations.

PHP Math: abs() function


The abs() function returns absolute value of given number. It returns an integer value but if
you pass floating point value, it returns a float value.

Syntax
1. number abs ( mixed $number )
Example
1. <?php
2. echo (abs(-7)."<br/>"); // 7 (integer)
3. echo (abs(7)."<br/>"); //7 (integer)
4. echo (abs(-7.2)."<br/>"); //7.2 (float/double)
5. ?>

Output:

7
7
7.2
PHP Math: ceil() function
The ceil() function rounds fractions up.

Syntax
1. float ceil ( float $value )
Example
1. <?php
2. echo (ceil(3.3)."<br/>");// 4
3. echo (ceil(7.333)."<br/>");// 8
4. echo (ceil(-4.8)."<br/>");// -4
5. ?>

Output:

4
8
-4

PHP Math: floor() function


The floor() function rounds fractions down.

Syntax
1. float floor ( float $value )
Example
1. <?php
2. echo (floor(3.3)."<br/>");// 3
3. echo (floor(7.333)."<br/>");// 7
4. echo (floor(-4.8)."<br/>");// -5
5. ?>

Output:

3
7
-5

PHP Math: sqrt() function


The sqrt() function returns square root of given argument.

Syntax
1. float sqrt ( float $arg )
Example
1. <?php
2. echo (sqrt(16)."<br/>");// 4
3. echo (sqrt(25)."<br/>");// 5
4. echo (sqrt(7)."<br/>");// 2.6457513110646
5. ?>

Output:

4
5
2.6457513110646

PHP Math: decbin() function


The decbin() function converts decimal number into binary. It returns binary number as a
string.

Syntax
1. string decbin ( int $number )
Example
1. <?php
2. echo (decbin(2)."<br/>");// 10
3. echo (decbin(10)."<br/>");// 1010
4. echo (decbin(22)."<br/>");// 10110
5. ?>

Output:

10
1010
10110

PHP Math: dechex() function


The dechex() function converts decimal number into hexadecimal. It returns hexadecimal
representation of given number as a string.

Syntax
1. string dechex ( int $number )
Example
1. <?php
2. echo (dechex(2)."<br/>");// 2
3. echo (dechex(10)."<br/>");// a
4. echo (dechex(22)."<br/>");// 16
5. ?>

Output:

2
a
16

PHP Math: decoct() function


The decoct() function converts decimal number into octal. It returns octal representation of
given number as a string.

Syntax
1. string decoct ( int $number )
Example
1. <?php
2. echo (decoct(2)."<br/>");// 2
3. echo (decoct(10)."<br/>");// 12
4. echo (decoct(22)."<br/>");// 26
5. ?>

Output:

2
12
26

PHP Math: base_convert() function


The base_convert() function allows you to convert any base number to any base number. For
example, you can convert hexadecimal number to binary, hexadecimal to octal, binary to
octal, octal to hexadecimal, binary to decimal etc.

Syntax
1. string base_convert ( string $number , int $frombase , int $tobase )
Example
1. <?php
2. $n1=10;
3. echo (base_convert($n1,10,2)."<br/>");// 1010
4. ?>

Output:

1010

PHP Math: bindec() function


The bindec() function converts binary number into decimal.

Syntax
1. number bindec ( string $binary_string )
Example
1. <?php
2. echo (bindec(10)."<br/>");// 2
3. echo (bindec(1010)."<br/>");// 10
4. echo (bindec(1011)."<br/>");// 11
5. ?>

Output:

2
10
11

PHP Math Functions


Let's see the list of important PHP math functions.

o abs()

o acos()

o acosh()

o asin()

o asinh()

o atan()

o atan2()

o atanh()

o base_convert()

o bindec()
o ceil()

o cos()

o cosh()

o decbin()

o dechex()

o decoct()

o deg2rad()

o exp()

o expm1()

o floor()

o fmod()

o getrandmax()

o hexdec()

o hypot()

o is_finite()

o is_infinite()

o is_nan()

o lcg_value()

o log()

o log10()

o log1p()

o max()

o min()

o mt_getrandmax()

o mt_rand()

o mt_srand()

o octdec()

o pi()

o pow()

o rad2deg()

o rand()

o round()
o sin()

o sinh()

o sqrt()

o srand()

o tan()

o tanh()

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

Output:
PHP
Include File
PHP allows you to include file so that a page content can be reused many times. There are
two ways to include file in PHP.

1. include

2. require

Advantage
Code Reusability: By the help of include and require construct, we can reuse HTML code or
PHP script in many PHP scripts.

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 include vs PHP require
If file is missing or inclusion fails, include allows the script to continue but require halts the
script producing a fatal E_COMPILE_ERROR level error.

PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user.

Cookie is created at server side and saved to client browser. Each time when client sends
request to the server, cookie is embedded with request. Such way, cookie can be received at
the server side.

In short, cookie can be created, sent and received at server end.

Note: PHP Cookie must be used before <html> tag.

PHP setcookie() function


PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you
can access it by $_COOKIE superglobal variable.

Syntax

1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

Example

1. setcookie("CookieName", "CookieValue");/* defining name and value only*/


2. setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*6
0 seconds or 3600 seconds)
3. setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.com", 1
);

PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.

Example
1. $value=$_COOKIE["CookieName"];//returns cookie value

PHP Cookie Example


File: cookie1.php

1. <?php
2. setcookie("user", "Sonoo");
3. ?>
4. <html>
5. <body>
6. <?php
7. if(!isset($_COOKIE["user"])) {
8. echo "Sorry, cookie is not found!";
9. } else {
10. echo "<br/>Cookie Value: " . $_COOKIE["user"];
11. }
12. ?>
13. </body>
14. </html>

Output:

Sorry, cookie is not found!

Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.

Output:

Cookie Value: Sonoo

PHP Delete Cookie


If you set the expiration date in past, cookie will be deleted.

File: cookie1.php

1. <?php
2. setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
3. ?>

PHP Session
PHP session is used to store and pass information from one page to another temporarily (until
user close the website).

PHP session technique is widely used in shopping websites where we need to store and pass
cart information e.g. username, product code, product name, product price etc from one page
to another.

PHP session creates unique user id for each browser to recognize the user and avoid conflict
between multiple browsers.

PHP session_start() function


PHP session_start() function is used to start the session. It starts a new or resumes existing
session. It returns existing session if session is created already. If session is not available, it
creates and returns new session.

Syntax

1. bool session_start ( void )

Example

1. session_start();

PHP $_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to set
and get session variable values.

Example: Store information


1. $_SESSION["user"] = "Sachin";

Example: Get information

1. echo $_SESSION["user"];

PHP Session Example


File: session1.php
1. <?php
2. session_start();
3. ?>
4. <html>
5. <body>
6. <?php
7. $_SESSION["user"] = "Sachin";
8. echo "Session information are set successfully.<br/>";
9. ?>
10. <a href="session2.php">Visit next page</a>
11. </body>
12. </html>
File: session2.php
1. <?php
2. session_start();
3. ?>
4. <html>
5. <body>
6. <?php
7. echo "User is: ".$_SESSION["user"];
8. ?>
9. </body>
10. </html>

PHP Session Counter Example


File: sessioncounter.php
1. <?php
2. session_start();
3.
4. if (!isset($_SESSION['counter'])) {
5. $_SESSION['counter'] = 1;
6. } else {
7. $_SESSION['counter']++;
8. }
9. echo ("Page Views: ".$_SESSION['counter']);
10. ?>

PHP Destroying Session


PHP session_destroy() function is used to destroy all session variables completely.

File: session3.php
1. <?php
2. session_start();
3. session_destroy();
4. ?>

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

1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resour
ce $context ]] )

Example

1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>
Click me for more details...
PHP Close File - fclose()
The PHP fclose() function is used to close an open file pointer.

Syntax

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

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

Output

hello php file


Click me for more details...

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


Click me for more details...

PHP Delete File - unlink()


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

Syntax

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

Example

1. <?php
2. unlink('data.txt');
3.
4. echo "File deleted successfully";
5. ?>

Click me for more details... PHP Open File


PHP fopen() function is used to open file or URL and returns resource. The fopen() function
accepts two arguments: $filename and $mode. The $filename represents the file to be
opended and $mode represents the file mode for example read-only, read-write, write-only
etc.

Syntax

1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resour
ce $context ]] )

PHP Open File Mode


Mode Description

r Opens file in read-only mode. It places the file pointer at the beginning of the file.

r+ Opens file in read-write mode. It places the file pointer at the beginning of the file.

w Opens file in write-only mode. It places the file pointer to the beginning of the file and trun
length. If file is not found, it creates a new file.

w+ Opens file in read-write mode. It places the file pointer to the beginning of the file and trun
length. If file is not found, it creates a new file.

a Opens file in write-only mode. It places the file pointer to the end of the file. If file is not found

a+ Opens file in read-write mode. It places the file pointer to the end of the file. If file is not found

x Creates and opens file in write-only mode. It places the file pointer at the beginning of the file. I
function returns FALSE.

x+ It is same as x but it creates and opens file in read-write mode.

c Opens file in write-only mode. If the file does not exist, it is created. If it exists, it is neither tr
to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on
file

c+ It is same as c but it opens file in read-write mode.

PHP Open File Example


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

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


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


In PHP, we can delete any file using unlink() function. The unlink() function accepts one
argument only: file name. It is similar to UNIX C unlink() function.

PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is
deleted successfully otherwise FALSE.

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

$filename represents the name of the file to be deleted.

PHP Delete File Example


1. <?php
2. $status=unlink('data.txt');
3. if($status){
4. echo "File deleted successfully";
5. }else{
6. echo "Sorry!";
7. }
8. ?>

Output

File deleted successfully

PHP File Upload


PHP allows you to upload single and multiple files through few lines of code only.

PHP file upload features allows you to upload binary and text files both. Moreover, you can
have the full control over the file to be uploaded through PHP authentication and file operation
functions.

PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we
can get file name, file type, file size, temp file name and errors associated with file.

Here, we are assuming that file name is filename.

$_FILES['filename']['name']
returns file name.

$_FILES['filename']['type']
returns MIME type of the file.
$_FILES['filename']['size']
returns size of the file (in bytes).

$_FILES['filename']['tmp_name']
returns temporary file name of the file which was stored on the server.

$_FILES['filename']['error']
returns error code associated with this file.

move_uploaded_file() function
The move_uploaded_file() function moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded thorough the POST
request. It moves the file if it is uploaded through the POST request.

Syntax

1. bool move_uploaded_file ( string $filename , string $destination )

PHP File Upload Example


File: uploadform.html

1. <form action="uploader.php" method="post" enctype="multipart/form-data">


2. Select File:
3. <input type="file" name="fileToUpload"/>
4. <input type="submit" value="Upload Image" name="submit"/>
5. </form>
File: uploader.php

1. <?php
2. $target_path = "e:/";
3. $target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
4.
5. if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
6. echo "File uploaded successfully!";
7. } else{
8. echo "Sorry, file not uploaded, please try again!";
9. }
10. ?>

PHP Download File


PHP enables you to download file easily using built-in readfile() function. The readfile()
function reads a file and writes it to the output buffer.

PHP readfile() function


Syntax

1. int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )

$filename: represents the file name

$use_include_path: it is the optional parameter. It is by default false. You can set it to true
to the search the file in the included_path.

$context: represents the context stream resource.

int: it returns the number of bytes read from the file.

PHP Download File Example: Text File


File: download1.php
1. <?php
2. $file_url = 'http://www.javatpoint.com/f.txt';
3. header('Content-Type: application/octet-stream');
4. header("Content-Transfer-Encoding: utf-8");
5. header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
6. readfile($file_url);
7. ?>

PHP Download File Example: Binary File


File: download2.php
1. <?php
2. $file_url = 'http://www.myremoteserver.com/file.exe';
3. header('Content-Type: application/octet-stream');
4. header("Content-Transfer-Encoding: Binary");
5. header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
6. readfile($file_url);
7. ?>

PHP Mail
PHP mail() function is used to send email in PHP. You can send text message, html message
and attachment with message using PHP mail() function.

PHP mail() function


Syntax

1. bool mail ( string $to , string $subject , string $message [, string $additional_headers [, stri
ng $additional_parameters ]] )

$to: specifies receiver or receivers of the mail. The receiver must be specified one of the
following forms.

o user@example.com

o user@example.com, anotheruser@example.com

o User <user@example.com>

o User <user@example.com>, Another User <anotheruser@example.com>

$subject: represents subject of the mail.

$message: represents message of the mail to be sent.

Note: Each line of the message should be separated with a CRLF ( \r\n ) and lines should not be larger
than 70 characters.

$additional_headers (optional): specifies the additional headers such as From, CC, BCC
etc. Extra additional headers should also be separated with CRLF ( \r\n ).

PHP Mail Example


File: mailer.php

1. <?php
2. ini_set("sendmail_from", "sonoojaiswal@javatpoint.com");
3. $to = "sonoojaiswal1987@gmail.com";//change receiver address
4. $subject = "This is subject";
5. $message = "This is simple text message.";
6. $header = "From:sonoojaiswal@javatpoint.com \r\n";
7.
8. $result = mail ($to,$subject,$message,$header);
9.
10. if( $result == true ){
11. echo "Message sent successfully...";
12. }else{
13. echo "Sorry, unable to send mail...";
14. }
15. ?>

If you run this code on the live server, it will send an email to the specified receiver.

PHP Mail: Send HTML Message


To send HTML message, you need to mention Content-type text/html in the message
header.

1. <?php
2. $to = "abc@example.com";//change receiver address
3. $subject = "This is subject";
4. $message = "<h1>This is HTML heading</h1>";
5.
6. $header = "From:xyz@example.com \r\n";
7. $header .= "MIME-Version: 1.0 \r\n";
8. $header .= "Content-type: text/html;charset=UTF-8 \r\n";
9.
10. $result = mail ($to,$subject,$message,$header);
11.
12. if( $result == true ){
13. echo "Message sent successfully...";
14. }else{
15. echo "Sorry, unable to send mail...";
16. }
17. ?>

PHP Mail: Send Mail with Attachment


To send message with attachment, you need to mention many header information which is
used in the example given below.

1. <?php
2. $to = "abc@example.com";
3. $subject = "This is subject";
4. $message = "This is a text message.";
5. # Open a file
6. $file = fopen("/tmp/test.txt", "r" );//change your file location
7. if( $file == false )
8. {
9. echo "Error in opening file";
10. exit();
11. }
12. # Read the file into a variable
13. $size = filesize("/tmp/test.txt");
14. $content = fread( $file, $size);
15.
16. # encode the data for safe transit
17. # and insert \r\n after every 76 chars.
18. $encoded_content = chunk_split( base64_encode($content));
19.
20. # Get a random 32 bit number using time() as seed.
21. $num = md5( time() );
22.
23. # Define the main headers.
24. $header = "From:xyz@example.com\r\n";
25. $header .= "MIME-Version: 1.0\r\n";
26. $header .= "Content-Type: multipart/mixed; ";
27. $header .= "boundary=$num\r\n";
28. $header .= "--$num\r\n";
29.
30. # Define the message section
31. $header .= "Content-Type: text/plain\r\n";
32. $header .= "Content-Transfer-Encoding:8bit\r\n\n";
33. $header .= "$message\r\n";
34. $header .= "--$num\r\n";
35.
36. # Define the attachment section
37. $header .= "Content-Type: multipart/mixed; ";
38. $header .= "name=\"test.txt\"\r\n";
39. $header .= "Content-Transfer-Encoding:base64\r\n";
40. $header .= "Content-Disposition:attachment; ";
41. $header .= "filename=\"test.txt\"\r\n\n";
42. $header .= "$encoded_content\r\n";
43. $header .= "--$num--";
44.
45. # Send email now
46. $result = mail ( $to, $subject, "", $header );
47. if( $result == true ){
48. echo "Message sent successfully...";
49. }else{
50. echo "Sorry, unable to send mail...";
51. }
52. ?>

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
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $conn = mysqli_connect($host, $user, $pass);
6. if(! $conn )
7. {
8. die('Could not connect: ' . mysqli_error());
9. }
10. echo 'Connected successfully';
11. mysqli_close($conn);
12. ?>

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
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $conn = mysqli_connect($host, $user, $pass);
6. if(! $conn )
7. {
8. die('Could not connect: ' . mysqli_connect_error());
9. }
10. echo 'Connected successfully<br/>';
11.
12. $sql = 'CREATE Database mydb';
13. if(mysqli_query( $conn,$sql)){
14. echo "Database mydb created successfully.";
15. }else{
16. echo "Sorry, database creation failed ".mysqli_error($conn);
17. }
18. mysqli_close($conn);
19. ?>

Output:

Connected successfully
Database mydb created successfully.

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
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $sql = "create table emp5(id INT AUTO_INCREMENT,name VARCHAR(20) NOT NULL,
14. emp_salary INT NOT NULL,primary key (id))";
15. if(mysqli_query($conn, $sql)){
16. echo "Table emp5 created successfully";
17. }else{
18. echo "Could not create table: ". mysqli_error($conn);
19. }
20.
21. mysqli_close($conn);
22. ?>

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
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $sql = 'INSERT INTO emp4(name,salary) VALUES ("sonoo", 9000)';
14. if(mysqli_query($conn, $sql)){
15. echo "Record inserted successfully";
16. }else{
17. echo "Could not insert record: ". mysqli_error($conn);
18. }
19.
20. mysqli_close($conn);
21. ?>

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
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $id=2;
14. $name="Rahul";
15. $salary=80000;
16. $sql = "update emp4 set name=\"$name\", salary=$salary where id=$id";
17. if(mysqli_query($conn, $sql)){
18. echo "Record updated successfully";
19. }else{
20. echo "Could not update record: ". mysqli_error($conn);
21. }
22.
23. mysqli_close($conn);
24. ?>

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
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $id=2;
14. $sql = "delete from emp4 where id=$id";
15. if(mysqli_query($conn, $sql)){
16. echo "Record deleted successfully";
17. }else{
18. echo "Could not deleted record: ". mysqli_error($conn);
19. }
20.
21. mysqli_close($conn);
22. ?>

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
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6. $conn = mysqli_connect($host, $user, $pass,$dbname);
7. if(!$conn){
8. die('Could not connect: '.mysqli_connect_error());
9. }
10. echo 'Connected successfully<br/>';
11.
12. $sql = 'SELECT * FROM emp4';
13. $retval=mysqli_query($conn, $sql);
14.
15. if(mysqli_num_rows($retval) > 0){
16. while($row = mysqli_fetch_assoc($retval)){
17. echo "EMP ID :{$row['id']} <br> ".
18. "EMP NAME : {$row['name']} <br> ".
19. "EMP SALARY : {$row['salary']} <br> ".
20. "--------------------------------<br>";
21. } //end of while
22. }else{
23. echo "0 results";
24. }
25. mysqli_close($conn);
26. ?>

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
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6. $conn = mysqli_connect($host, $user, $pass,$dbname);
7. if(!$conn){
8. die('Could not connect: '.mysqli_connect_error());
9. }
10. echo 'Connected successfully<br/>';
11.
12. $sql = 'SELECT * FROM emp4 order by name';
13. $retval=mysqli_query($conn, $sql);
14.
15. if(mysqli_num_rows($retval) > 0){
16. while($row = mysqli_fetch_assoc($retval)){
17. echo "EMP ID :{$row['id']} <br> ".
18. "EMP NAME : {$row['name']} <br> ".
19. "EMP SALARY : {$row['salary']} <br> ".
20. "--------------------------------<br>";
21. } //end of while
22. }else{
23. echo "0 results";
24. }
25. mysqli_close($conn);
26. ?>

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

PHP Interview Questions


There is given PHP interview questions and answers that has been asked in many companies.
Let's see the list of top PHP interview questions.

1) What is PHP?
PHP stands for Hypertext Preprocessor. It is an open source server-side scripting language
which is widely used for web development. It supports many databases like MySQL, Oracle,
Sybase, Solid, PostgreSQL, generic ODBC etc.
More Details...

2) What is PEAR in PHP?


PEAR is a framework and repository for reusable PHP components. PEAR stands for PHP
Extension and Application Repository. It contains all types of PHP code snippets and
libraries.

It also provides a command line interface to install "packages" automatically.

3) Who is known as the father of PHP?


Rasmus Lerdorf

4) What was the old name of PHP?


Personal Home Page.

5) Explain the difference b/w static and dynamic websites?


In static websites, content can't be changed after running the script. You can't change
anything in the site. It is predefined.

In dynamic websites, content of script can be changed at the run time. Its content is
regenerated every time a user visit or reload. Google, yahoo and every search engine is the
example of dynamic website.

6) What is the name of scripting engine in PHP?


The scripting engine that powers PHP is called Zend Engine 2.

7) Explain the difference between PHP4 and PHP5.


PHP4 doesn't support oops concept and uses Zend Engine 1.

PHP5 supports oops concept and uses Zend Engine 2.


8) What are the popular Content Management Systems (CMS)
in PHP?
o WordPress

o Joomla

o Magento

o Drupal etc.

9) What are the popular frameworks in PHP?


o CakePHP

o CodeIgniter

o Yii 2

o Symfony

o Zend Framework etc.

10) Which programming language does PHP resemble to?


PHP has borrowed its syntax from Perl and C.

11) List some of the features of PHP7.


o Scalar type declarations

o Return type declarations

o Null coalescing operator (??)

o Spaceship operator

o Constant arrays using define()

o Anonymous classes

o Closure::call method

o Group use declaration

o Generator return expressions

o Generator delegation

o Space ship operator


12) What is "echo" in PHP?
PHP echo output one or more string. It is a language construct not a function. So use of
parentheses is not required. But if you want to pass more than one parameter to echo, use
of parentheses is required.

Syntax:

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


More details...

13) What is "print" in PHP?


PHP print output a string. It is a language construct not a function. So use of parentheses is
not required with the argument list. Unlike echo, it always returns 1.

Syntax:

1. int print ( string $arg)


More details...

14) What is the difference between "echo" and "print" in PHP?


Echo can output one or more string but print can only output one string and always returns
1.

Echo is faster than print because it does not return any value.

15) How a variable is declared in PHP?


PHP variable is a name of memory location that holds data. It is a temporary storage.

Syntax:

1. $variableName=value;
More details...
16) What is the difference between $message and
$$message?
$message stores variable data while $$message is used to store variable of variables.

$message stores fixed data whereas the data stored in $$message may be changed
dynamically.

More Details...

17) What are the ways to define a constant in PHP?


PHP constants are name or identifier that can't be changed during execution of the script. PHP
constants are defined in two ways:

o Using define() function

o Using const() function

More details...

18) What are magic constants in PHP?


PHP magic constants are predefined constants which changes on the basis of their use. They
start with a double underscore (__) and end with a double underscore (__).

More Details...

19) How many data types are there in PHP?


PHP data types are used to hold different types of data or values. There are 8 primitive data
types which are further categorized in 3 types:

o Scalar types

o Compound types

o Special types

More Details...
20) How to do single and multi line comment in PHP?
PHP single line comment is done in two ways:

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

o Using # (Unix Shell style single line comment)

PHP multi line comment is done by enclosing all lines within /* */.

More details...

21) What are the different loops in PHP?


For, while, do-while and for each.

22) What is the use of count() function in PHP?


The PHP count() function is used to count total elements in the array, or something an object.

23) What is the use of header() function in PHP?


The header() function is used to send a raw HTTP header to a client. It must be called before
sending the actual output. For example, you can't print any HTML element before using this
function.

24) What does isset() function?


The isset() function checks if the variable is defined and not null.

25) Explain PHP parameterized functions.


PHP parameterized functions are 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 function name. Output depends upon dynamic
values passed as parameters into function.

More details...
26) Explain PHP variable length argument function
PHP supports variable length argument function. It means you can pass 0, 1 or n number of
arguments in function. To do this, you need to use 3 ellipses (dots) before the argument
name. The 3 dot concept is implemented for variable length argument since PHP 5.6.

More details...

27) Explain PHP variable length argument function.


PHP supports variable length argument function. It means you can pass 0, 1 or n number of
arguments.

28) What is the array in PHP?


Array is used to store multiple values in single value. In PHP, it orders maps of pairs of keys
and values. It stores the collection of data type.

More Details...

29) How many types of array are there in PHP?


There are three types of array in PHP:

o Indexed array

o Associative array

o Multidimensional array

30) Explain some of the PHP array functions?


There are many array functions in PHP:

o array()

o array_change_key_case()

o array_chunk()

o count()
o sort()

o array_reverse()

o array_search()

o array_intersect()

More details...

31) What is the difference between indexed and associative


array?
The indexed array holds elements in an indexed form which is represented by number starting
from 0 and incremented by 1. For example:

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

The associative array holds elements with name. For example:

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

More Details...

32) How to get the length of string?


The strlen() function is used to get the length of string.

More Details...

33) Explain some of the PHP string functions?


There are many array functions in PHP:

o strtolower()

o strtoupper()

o ucfirst()

o lcfirst()

o ucwords()

o strrev()
o strlen()

More details...

34) What are the methods to submit form in PHP?


There are two methods GET and POST.

More Details...

35) How can you submit a form without a submit button?


You can use JavaScript submit() function to submit the form without explicitly clicking any
submit button.

36) What are the ways to include file in PHP?


PHP allows you to include file so that page content can be reused again. There are two ways
to include file in PHP.

1. include

2. require

More details...

37) Differentiate between require and include?


Require and include both are used to include a file, but if file is not found include sends
warning whereas require sends Fatal error.

More Details...

38) Explain setcookie() function in PHP?


PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you
can access it by $_COOKIE superglobal variable.

Syntax:

1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
More details...

39) How can you retrieve a cookie value?


1. echo $_COOKIE ["user"];
More Details...

40) What is a session?


PHP Engine creates a logical object to preserve data across subsequent HTTP requests, which
is known as session.

Sessions generally store temporary data to allow multiple PHP pages to offer a complete
functional transaction for the same user.

Simply, it maintains data of an user (browser).

More Details...

41) What is the method to register a variable into a session?


1. <?php
2. Session_register($ur_session_var);
3. ?>

42) What is $_SESSION in PHP?


PHP $_SESSION is an associative array that contains all session variables. It is used to set
and get session variable values.

More details...

43) What is PHP session_start() and session_destroy()


function?
PHP session_start() function is used to start the session. It starts a new or resumes the
existing session. It returns the existing session if session is created already. If session is not
available, it creates and returns new sessions.

More details...
44) What is the difference between session and cookie?
The main difference between session and cookie is that cookies are stored on user's computer
in the text file format while sessions are stored on the server side.

Cookies can't hold multiple variables on the other hand Session can hold multiple variables.

You can manually set an expiry for a cookie, while session only remains active as long as
browser is open.

45) Write syntax to open a file in PHP?


PHP fopen() function is used to open file or URL and returns resource. It accepts two
arguments: $filename and $mode.

Syntax:

1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resour
ce $context ]] )
More details...

46) How to read a file in PHP?


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.

PHP file read functions are given below:

o fread()

o fgets()

o fgetc()

More details...

47) How to write in a file in PHP?


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.

More details...
48) How to delete file in PHP?
The unlink() function is used to delete file in PHP.

1. bool unlink (string $filename)

More Details...

49) What is the method to execute a PHP script from the


command line?
You should just run the PHP command line interface (CLI) and specify the file name of the
script to be executed as follows.

50) How to upload file in PHP?


The move_uploaded_file() function is used to upload file in PHP.

1. bool move_uploaded_file ( string $filename , string $destination )

More Details...

51) How to download file in PHP?


The readfile() function is used to download file in PHP.

1. int readfile ( string $filename )

More Details...

52) How can you send email in PHP?


The mail() function is used to send email in PHP.

1. bool mail($to,$subject,$message,$header);
More Details...

53) How do you connect MySQL database with PHP?


There are two methods to connect MySQL database with PHP. Procedural and object oriented
style.

More Details...

54) How to create connection in PHP?


The mysqli_connect() function is used to create connection in PHP.

1. resource mysqli_connect (server, username, password)

More Details...

55) How to create database connection and query in PHP?


Since PHP 4.3, mysql_reate_db() is deprecated. Now you can use following 2 alternatives.

o mysqli_query()

o PDO::_query()

More details...

56) How can we increase execution time of a PHP script?


By default, maximum execution time for PHP scripts is set to 30 seconds. If a script takes
more than 30 seconds, PHP stops the script and returns an error.

You can change the script run time by changing the max_execution_time directive in php.ini
file.

When a script is called, set_time_limit function restarts the timeout counter from zero. It
means, if default timer is set to 30 sec, and 20 sec is specified in function set_time_limit(),
then script will run for 45 seconds. If 0sec is specified in this function, script takes unlimited
time.
57) What are the different types of errors in PHP?
There are 3 types of error in PHP.

Notices:These are non-critical errors. These errors are not displayed to the users.

Warnings:These are more serious errors but they do not result in script termination. By
default, these errors are displayed to the user.

Fatal Errors:These are the most critical errors. These errors may cause due to immediate
termination of script.

58) How to stop the execution of PHP script?


The exit() function is used to stop the execution of PHP script.

59) What are the encryption functions in PHP?


CRYPT() and MD5()

60) What is htaccess in PHP?


The .htaccess is a configuration file on Apache server. You can change configuration settings
using directives in Apache configuration files like .htaccess and httpd.conf.

61) Explain PHP explode() function.


The PHP explode() function breaks a string into an array.

62) Explain PHP split() function.


The PHP split() function splits string into an array by regular expression.

63) How can we get IP address of a client in PHP?


1. $_SERVER["REMOTE_ADDR"];
PHP JSON
PHP allows us to encode and decode JSON by the help of json_encode() and json_decode
functions.

1) PHP json_encode
The json_encode() function returns the JSON representation of a value. In other words, it
converts PHP variable (containing array) into JSON.

Syntax:

1. string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )


PHP json_encode example 1
Let's see the example to encode JSON.

1. <?php
2. $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
3. echo json_encode($arr);
4. ?>

Output

{"a":1,"b":2,"c":3,"d":4,"e":5}
PHP json_encode example 2
Let's see the example to encode JSON.

1. <?php
2. $arr2 = array('firstName' => 'Rahul', 'lastName' => 'Kumar', 'email' => 'rahul@gmail.com')
;
3. echo json_encode($arr2);
4. ?>

Output

{"firstName":"Rahul","lastName":"Kumar","email":"rahul@gmail.com"}

2) PHP json_decode
The json_decode() function decodes the JSON string. In other words, it converts JSON string
into a PHP variable.

Syntax:

1. mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options
= 0 ]]] )
PHP json_decode example 1
Let's see the example to decode JSON string.

1. <?php
2. $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
3. var_dump(json_decode($json, true));//true means returned object will be converted i
nto associative array
4. ?>

Output

array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
PHP json_decode example 2
Let's see the example to decode JSON string.

1. <?php
2. $json2 = '{"firstName" : "Rahul", "lastName" : "Kumar", "email" : "rahul@gmail.com"}';
3. var_dump(json_decode($json2, true));
4. ?>

Output

array(3) {
["firstName"]=> string(5) "Rahul"
["lastName"]=> string(5) "Kumar"
["email"]=> string(15) "rahul@gmail.com"
}

Das könnte Ihnen auch gefallen