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
PHP is an open-source, interpreted, and object-oriented scripting language that can be executed at the server-side. PHP is well suited for web development. Therefore, it is used to develop web applications (an application that executes on the server and generates the dynamic page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 7.4.0 is the latest version of PHP, which was released on 28 November. Some important points need to be noticed about PHP are as followed:
Pause
https://techzone360.shop/php-tutorials/Next
Mute
Current Time
0:23
/
Duration
18:10
Fullscreen
PHP stands for Hypertext Preprocessor.
PHP is an interpreted language, i.e., there is no need for compilation.
PHP is faster than other scripting languages, for example, ASP and JSP.
PHP is a server-side scripting language, which is used to manage the dynamic content of the website.
PHP can be embedded into HTML.
PHP is an object-oriented language.
PHP is an open-source scripting language.
PHP is simple and easy to learn language.
What is PHP
PHP Example
Test it Now
Output:
Hello, World!
Why use PHP
PHP is a server-side scripting language, which is used to design the dynamic web applications with MySQL database.
It handles dynamic content, database as well as session tracking for the website.
You can create sessions in PHP.
It can access cookies variable and also set cookies.
It helps to encrypt the data and apply validation.
PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many more.
Using PHP language, you can control the user to access some pages of your website.
As PHP is easy to install and set up, this is the main reason why PHP is the best language to learn.
PHP can handle the forms, such as – collect the data from users using forms, save it into the database, and return useful information to the user. For example – Registration form.
PHP Features
PHP is very popular language because of its simplicity and open source. There are some important features of PHP given below:
PHP Features
Performance:
PHP script is executed much faster than those scripts which are written in other languages such as JSP and ASP. PHP uses its own memory, so the server workload and loading time is automatically reduced, which results in faster processing speed and better performance.
Open Source:
PHP source code and software are freely available on the web. You can develop all the versions of PHP according to your requirement without paying any cost. All its components are free to download and use.
Familiarity with syntax:
PHP has easily understandable syntax. Programmers are comfortable coding with it.
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application developed in one OS can be easily executed in other OS also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting –
PHP has predefined error reporting constants to generate an error notice or warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language:
PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the time of execution based on the type of data it contains on its value.
Web servers Support:
PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS, etc.
Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to prevent threads and malicious attacks.
Control:
Different programming languages require long script or code, whereas PHP can do the same work in a few lines of code. It has maximum control over the websites like you can make changes easily whenever you want.
A Helpful PHP Community:
It has a large community of developers who regularly updates documentation, tutorials, online help, and FAQs. Learning PHP from the communities is one of the significant benefits.
Web Development
PHP is widely used in web development nowadays. PHP can develop dynamic websites easily. But you must have the basic the knowledge of following technologies for web development as well.
HTML
CSS
JavaScript
Ajax
XML and JSON
jQuery
Prerequisite
Before learning PHP, you must have the basic knowledge of HTML, CSS, and JavaScript. So, learn these technologies for better implementation of PHP.
HTML – HTML is used to design static webpage.
CSS – CSS helps to make the webpage content more effective and attractive.
JavaScript – JavaScript is used to design an interactive website.
PHP If Else
PHP if else statement is used to test condition. There are various ways to use if statement in PHP.
if
if-else
if-else-if
nested if
PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition is true.
If statement is used to executes the block of code exist inside the if statement only if the specified condition is true.
Syntax
Pause
Next
Mute
Current Time
0:10
/
Duration
18:10
Fullscreen
if(condition){
//code to be executed
}
Flowchart
php if statement flowchart
Example
Output:
12 is less than 100
PHP If-else Statement
PHP if-else statement is executed whether condition is true or false.
If-else statement is slightly different from if statement. It executes one block of code if the specified condition is true and another block of code if the condition is false.
Syntax
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}
Flowchart
php if-else statement flowchart
Example
Output:
12 is even number
PHP If-else-if Statement
The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we can check multiple conditions using this statement.
Syntax
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
….
} else{
//code to be executed if all given conditions are false
}
Flowchart
php if-else statement flowchart
Example
=34 && $marks<50) { echo “D grade”; } else if ($marks>=50 && $marks<65) { echo “C grade”; } else if ($marks>=65 && $marks<80) { echo “B grade”; } else if ($marks>=80 && $marks<90) { echo “A grade”; } else if ($marks>=90 && $marks<100) { echo “A+ grade”; } else { echo “Invalid input”; } ?>
Output:
B Grade
PHP nested if Statement
The nested if statement contains the if block inside another if block. The inner if statement executes only when specified condition in outer if statement is true.
Syntax
if (condition) {
//code to be executed if condition is true
if (condition) {
//code to be executed if condition is true
}
}
Flowchart
php if-else statement flowchart
Example
= 18) {
echo “Eligible to give vote”;
}
else {
echo “Not eligible to give vote”;
}
}
?>
Output:
PHP Programs
PHP programs are frequently asked in the interview. These programs can be asked from basics, control statements, array, string, oops, file handling etc. Let’s see the list of top PHP programs.
1) Sum of Digits
Write a PHP program to print sum of digits.
Input: 23
Output: 5
Input: 624
Output: 12
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
https://googleads.g.doubleclick.net/pagead/ads?gdpr=0&client=ca-pub-4699858549023382&output=html&h=0&slotname=6746133113&adk=4015322468&adf=3256916255&pi=t.ma~as.6746133113&w=0&abgtt=1&lmt=1739529117&rafmt=12&format=0x0&url=https%3A%2F%2Fwww.tpointtech.com%2Fphp-programs&wgl=1&uach=WyJXaW5kb3dzIiwiMTAuMC4wIiwieDg2IiwiIiwiMTMxLjAuMjkwMy4xMTIiLG51bGwsMCxudWxsLCI2NCIsW1siTWljcm9zb2Z0IEVkZ2UiLCIxMzEuMC4yOTAzLjExMiJdLFsiQ2hyb21pdW0iLCIxMzEuMC42Nzc4LjIwNSJdLFsiTm90X0EgQnJhbmQiLCIyNC4wLjAuMCJdXSwwXQ..&dt=1739529114211&bpp=7&bdt=154&idt=373&shv=r20250211&mjsv=m202502110101&ptt=9&saldr=aa&abxe=1&cookie=ID%3Ddb3c093a58ddf978%3AT%3D1739528718%3ART%3D1739529037%3AS%3DALNI_MZ1JhPoWJvh4T7s830j2V2lNjh1JA&gpic=UID%3D00001039c9897216%3AT%3D1739528718%3ART%3D1739529037%3AS%3DALNI_MZa5qsV3OjehhY6Y1jGvZilSpDffw&eo_id_str=ID%3Dcb36373651058d51%3AT%3D1739528718%3ART%3D1739529037%3AS%3DAA-AfjYynbLU8QkKqubLPXiy2syE&prev_fmts=0x0&nras=1&correlator=6849004218408&frm=20&pv=1&u_tz=330&u_his=7&u_h=900&u_w=1600&u_ah=860&u_aw=1600&u_cd=24&u_sd=1&dmc=8&adx=282&ady=4227&biw=1011&bih=732&scr_x=0&scr_y=1309&eid=31090152%2C31090259%2C31090263%2C31090352%2C95344790%2C95352068%2C95347433%2C95350016%2C95340253%2C95340255&oid=2&pvsid=1469325562708546&tmod=2127287631&wsm=1&uas=3&nvt=1&ref=https%3A%2F%2Fwww.tpointtech.com%2Fphp-for-loop&fc=896&brdim=493%2C22%2C493%2C22%2C1600%2C0%2C1050%2C840%2C1026%2C747&vis=1&rsz=o%7C%7CoeEbr%7C&abl=CS&fu=1280&bc=31&bz=1.02&td=1&tdf=2&psd=W251bGwsbnVsbCxudWxsLDNd&nt=1&ifi=1&uci=a!1&btvi=1&fsb=1&dtd=2844
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:
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
- function functionname(){
- //code to be executed
- }
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.
https://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-4699858549023382&output=html&h=0&slotname=6746133113&adk=4015322468&adf=3256916255&pi=t.ma~as.6746133113&w=0&abgtt=1&lmt=1739529381&rafmt=12&format=0x0&url=https%3A%2F%2Fwww.tpointtech.com%2Fphp-functions&wgl=1&uach=WyJXaW5kb3dzIiwiMTAuMC4wIiwieDg2IiwiIiwiMTMxLjAuMjkwMy4xMTIiLG51bGwsMCxudWxsLCI2NCIsW1siTWljcm9zb2Z0IEVkZ2UiLCIxMzEuMC4yOTAzLjExMiJdLFsiQ2hyb21pdW0iLCIxMzEuMC42Nzc4LjIwNSJdLFsiTm90X0EgQnJhbmQiLCIyNC4wLjAuMCJdXSwwXQ..&dt=1739529381385&bpp=3&bdt=163&idt=29&shv=r20250211&mjsv=m202502110101&ptt=9&saldr=aa&abxe=1&cookie=ID%3Ddb3c093a58ddf978%3AT%3D1739528718%3ART%3D1739529376%3AS%3DALNI_MZ1JhPoWJvh4T7s830j2V2lNjh1JA&gpic=UID%3D00001039c9897216%3AT%3D1739528718%3ART%3D1739529376%3AS%3DALNI_MZa5qsV3OjehhY6Y1jGvZilSpDffw&eo_id_str=ID%3Dcb36373651058d51%3AT%3D1739528718%3ART%3D1739529376%3AS%3DAA-AfjYynbLU8QkKqubLPXiy2syE&correlator=3676439507307&frm=20&pv=2&u_tz=330&u_his=8&u_h=900&u_w=1600&u_ah=860&u_aw=1600&u_cd=24&u_sd=1&dmc=8&adx=314&ady=1291&biw=1577&bih=782&scr_x=0&scr_y=0&eid=31089910%2C31090260%2C31090263%2C95332928%2C95344788%2C95352068%2C95347433%2C95350016%2C31061690&oid=2&pvsid=2638155241411346&tmod=2127287631&wsm=1&uas=0&nvt=1&ref=https%3A%2F%2Fwww.tpointtech.com%2Fphp-programs&fc=640&brdim=0%2C0%2C0%2C0%2C1600%2C0%2C1600%2C860%2C1592%2C782&vis=1&rsz=o%7C%7CoeEbr%7C&abl=CS&fu=256&bc=31&bz=1.01&td=1&tdf=2&psd=W251bGwsbnVsbCxudWxsLDNd&nt=1&ifi=1&uci=a!1&btvi=1&fsb=1&dtd=45
PHP Functions Example
File: function1.php
- <?php
- function sayHello(){
- echo “Hello PHP Function”;
- }
- sayHello();//calling function
- ?>
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
- <?php
- function sayHello($name){
- echo “Hello $name<br/>”;
- }
- sayHello(“Sonoo”);
- sayHello(“Vimal”);
- sayHello(“John”);
- ?>
Output:
Hello Sonoo Hello Vimal Hello John
Let’s see the example to pass two argument in PHP function.File: functionarg2.php
- <?php
- function sayHello($name,$age){
- echo “Hello $name, you are $age years old<br/>”;
- }
- sayHello(“Sonoo”,27);
- sayHello(“Vimal”,29);
- sayHello(“John”,23);
- ?>
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
- <?php
- function adder(&$str2)
- {
- $str2 .= ‘Call By Reference’;
- }
- $str = ‘Hello ‘;
- adder($str);
- echo $str;
- ?>
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
- <?php
- function sayHello($name=”Sonoo”){
- echo “Hello $name<br/>”;
- }
- sayHello(“Rajesh”);
- sayHello();//passing no value
- sayHello(“John”);
- ?>
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
- <?php
- function cube($n){
- return $n*$n*$n;
- }
- echo “Cube of 3 is: “.cube(3);
- ?>
Output:
Cube of 3 is: 27
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.PauseNextMute
Current Time 0:09
/
Duration 18:10
Loaded: 4.77%Fullscreen
PHP Array Types
There are 3 types of array in PHP.
- Indexed Array
- Associative Array
- Multidimensional Array
PHP Indexed Array
PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array. All PHP array elements are assigned to an index number by default.
There are two ways to define indexed array:
1st way:
- $season=array(“summer”,”winter”,”spring”,”autumn”);
2nd way:
- $season[0]=”summer”;
- $season[1]=”winter”;
- $season[2]=”spring”;
- $season[3]=”autumn”;
Example
File: array1.php
- <?php
- $season=array(“summer”,”winter”,”spring”,”autumn”);
- echo “Season are: $season[0], $season[1], $season[2] and $season[3]”;
- ?>
Output:
Season are: summer, winter, spring and autumnFile: array2.php
- <?php
- $season[0]=”summer”;
- $season[1]=”winter”;
- $season[2]=”spring”;
- $season[3]=”autumn”;
- echo “Season are: $season[0], $season[1], $season[2] and $season[3]”;
- ?>
Output:
Season are: summer, winter, spring and autumn
https://googleads.g.doubleclick.net/pagead/ads?gdpr=0&client=ca-pub-4699858549023382&output=html&h=0&slotname=6746133113&adk=4015322468&adf=3256916255&pi=t.ma~as.6746133113&w=0&abgtt=1&lmt=1739529513&rafmt=12&format=0x0&url=https%3A%2F%2Fwww.tpointtech.com%2Fphp-array&wgl=1&uach=WyJXaW5kb3dzIiwiMTAuMC4wIiwieDg2IiwiIiwiMTMxLjAuMjkwMy4xMTIiLG51bGwsMCxudWxsLCI2NCIsW1siTWljcm9zb2Z0IEVkZ2UiLCIxMzEuMC4yOTAzLjExMiJdLFsiQ2hyb21pdW0iLCIxMzEuMC42Nzc4LjIwNSJdLFsiTm90X0EgQnJhbmQiLCIyNC4wLjAuMCJdXSwwXQ..&dt=1739529512899&bpp=7&bdt=332&idt=283&shv=r20250211&mjsv=m202502110101&ptt=9&saldr=aa&abxe=1&cookie=ID%3Ddb3c093a58ddf978%3AT%3D1739528718%3ART%3D1739529376%3AS%3DALNI_MZ1JhPoWJvh4T7s830j2V2lNjh1JA&gpic=UID%3D00001039c9897216%3AT%3D1739528718%3ART%3D1739529376%3AS%3DALNI_MZa5qsV3OjehhY6Y1jGvZilSpDffw&eo_id_str=ID%3Dcb36373651058d51%3AT%3D1739528718%3ART%3D1739529376%3AS%3DAA-AfjYynbLU8QkKqubLPXiy2syE&correlator=1659290457541&frm=20&pv=2&u_tz=330&u_his=9&u_h=900&u_w=1600&u_ah=860&u_aw=1600&u_cd=24&u_sd=1&dmc=8&adx=314&ady=2833&biw=1577&bih=782&scr_x=0&scr_y=0&eid=31090148%2C95352068%2C95347433%2C95350016&oid=2&pvsid=2159473939382098&tmod=2127287631&wsm=1&uas=0&nvt=1&ref=https%3A%2F%2Fwww.tpointtech.com%2Fphp-functions&fc=896&brdim=0%2C0%2C0%2C0%2C1600%2C0%2C1600%2C860%2C1592%2C782&vis=1&rsz=o%7C%7CoeEbr%7C&abl=CS&fu=256&bc=31&bz=1.01&td=1&tdf=2&psd=W251bGwsbnVsbCxudWxsLDNd&nt=1&ifi=1&uci=a!1&btvi=1&fsb=1&dtd=893
PHP Associative Array
We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:
1st way:
- $salary=array(“Sonoo”=>”350000″,”John”=>”450000″,”Kartik”=>”200000”);
2nd way:
- $salary[“Sonoo”]=”350000″;
- $salary[“John”]=”450000″;
- $salary[“Kartik”]=”200000″;
Example
File: arrayassociative1.php
- <?php
- $salary=array(“Sonoo”=>”350000″,”John”=>”450000″,”Kartik”=>”200000”);
- echo “Sonoo salary: “.$salary[“Sonoo”].”<br/>”;
- echo “John salary: “.$salary[“John”].”<br/>”;
- echo “Kartik salary: “.$salary[“Kartik”].”<br/>”;
- ?>
Output:
Sonoo salary: 350000 John salary: 450000 Kartik salary: 200000
File: arrayassociative2.php
- <?php
- $salary[“Sonoo”]=”350000″;
- $salary[“John”]=”450000″;
- $salary[“Kartik”]=”200000″;
- echo “Sonoo salary: “.$salary[“Sonoo”].”<br/>”;
- echo “John salary: “.$salary[“John”].”<br/>”;
- echo “Kartik salary: “.$salary[“Kartik”].”<br/>”;
- ?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000
PHP String
PHP string is a sequence of characters i.e., used to store and manipulate text. PHP supports only 256-character set and so that it does not offer native Unicode support. There are 4 ways to specify a string literal in PHP.
- single quoted
- double quoted
- heredoc syntax
- newdoc syntax (since PHP 5.3)
Single Quoted
We can create a string in PHP by enclosing the text in a single-quote. It is the easiest way to specify string in PHP.
For specifying a literal single quote, escape it with a backslash (\) and to specify a literal backslash (\) use double backslash (\\). All the other instances with backslash such as \r or \n, will be output same as they specified instead of having any special meaning.
For Example
Following some examples are given to understand the single quoted PHP String in a better way:PauseNextMute
Current Time 0:32
/
Duration 18:10
Loaded: 8.81%Fullscreen
Example 1
- <?php
- $str=’Hello text within single quote’;
- echo $str;
- ?>
Output:
Hello text within single quote
We can store multiple line text, special characters, and escape sequences in a single-quoted PHP string.
Example 2
- <?php
- $str1=’Hello text
- multiple line
- text within single quoted string’;
- $str2=’Using double “quote” directly inside single quoted string’;
- $str3=’Using escape sequences \n in single quoted string’;
- echo “$str1 <br/> $str2 <br/> $str3”;
- ?>
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
Example 3
- <?php
- $num1=10;
- $str1=’trying variable $num1′;
- $str2=’trying backslash n and backslash t inside single quoted string \n \t’;
- $str3=’Using single quote \’my quote\’ and \\backslash’;
- echo “$str1 <br/> $str2 <br/> $str3”;
- ?>
Output:
trying variable $num1 trying backslash n and backslash t inside single quoted string \n \t Using single quote 'my quote' and \backslash
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.
Double Quoted
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.
Example 1
- <?php
- $str=”Hello text within double quote”;
- echo $str;
- ?>
Output:
Hello text within double quote
Now, you can’t use double quote directly inside double quoted string.
Example 2
- <?php
- $str1=”Using double “quote” directly inside double quoted string”;
- echo $str1;
- ?>
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.
Example 3
- <?php
- $str1=”Hello text
- multiple line
- text within double quoted string”;
- $str2=”Using double \”quote\” with backslash inside double quoted string”;
- $str3=”Using escape sequences \n in double quoted string”;
- echo “$str1 <br/> $str2 <br/> $str3”;
- ?>
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.
Example 4
- <?php
- $num1=10;
- echo “Number is: $num1”;
- ?>
Output:
Number is: 10
Heredoc
Heredoc syntax (<<<) is the third way to delimit strings. In Heredoc syntax, an identifier is provided after this heredoc <<< operator, and immediately a new line is started to write any text. To close the quotation, the string follows itself and then again that same identifier is provided. That closing identifier must begin from the new line without any whitespace or tab.
Naming Rules
The identifier should follow the naming rule that it must contain only alphanumeric characters and underscores, and must start with an underscore or a non-digit character.
For Example
Valid Example
- <?php
- $str = <<<Demo
- It is a valid example
- Demo; //Valid code as whitespace or tab is not valid before closing identifier
- echo $str;
- ?>
Output:
It is a valid example
Invalid Example
We cannot use any whitespace or tab before and after the identifier and semicolon, which means identifier must not be indented. The identifier must begin from the new line.
- <?php
- $str = <<<Demo
- It is Invalid example
- Demo; //Invalid code as whitespace or tab is not valid before closing identifier
- echo $str;
- ?>
This code will generate an error.
Output:
Parse error: syntax error, unexpected end of file in C:\xampp\htdocs\xampp\PMA\heredoc.php on line 7
Heredoc is similar to the double-quoted string, without the double quote, means that quote in a heredoc are not required. It can also print the variable’s value.
Example
- <?php
- $city = ‘Delhi’;
- $str = <<<DEMO
- Hello! My name is Mishti, and I live in $city.
- DEMO;
- echo $str;
- ?>
Output:
Hello! My name is Misthi, and I live in Delhi.
Example
We can add multiple lines of text here between heredoc syntax.
- <?php
- $str = <<<DEMO
- It is the example
- of multiple
- lines of text.
- DEMO;
- echo $str;
- echo ‘</br>’;
- echo <<<DEMO // Here we are not storing string content in variable str.
- It is the example
- of multiple
- lines of text.
- DEMO;
- ?>
Output:
It is the example of multiple lines of text. It is the example of multiple lines of text.
Below are the example with class and their variable
Example
- <?php
- class heredocExample{
- var $demo;
- var $example;
- function __construct()
- {
- $this->demo = ‘DEMO’;
- $this->example = array(‘Example1’, ‘Example2’, ‘Example3’);
- }
- }
- $heredocExample = new heredocExample();
- $name = ‘Gunjan’;
- echo <<<ECO
- My name is “$name”. I am printing some $heredocExample->demo example.
- Now, I am printing {$heredocExample->example[1]}.
- It will print a capital ‘A’: \x41
- ECO;
- ?>
Output:
My name is "Gunjan". I am printing some DEMO example. Now, I am printing Example2. It will print a capital 'A': A
Newdoc
Newdoc is similar to the heredoc, but in newdoc parsing is not done. It is also identified with three less than symbols <<< followed by an identifier. But here identifier is enclosed in single-quote, e.g. <<<‘EXP’. Newdoc follows the same rule as heredocs.
The difference between newdoc and heredoc is that – Newdoc is a single-quoted string whereas heredoc is a double-quoted string.
Note: Newdoc works as single quotes.
Example-1:
- <?php
- $str = <<<‘DEMO’
- Welcome to javaTpoint.
- Learn with newdoc example.
- DEMO;
- echo $str;
- echo ‘</br>’;
- echo <<< ‘Demo’ // Here we are not storing string content in variable str.
- Welcome to javaTpoint.
- Learn with newdoc example.
- Demo;
- ?>
Output:
Welcome to javaTpoint. Learn with newdoc example. Welcome to javaTpoint. Learn with newdoc example.
Go to view page source and see the source of the program.
Example
The below example shows that newdoc does not print the variable’s value.
- <?php
- class heredocExample{
- var $demo;
- var $example;
- function __construct()
- {
- $this->demo = ‘DEMO’;
- $this->example = array(‘Example1’, ‘Example2’, ‘Example3’);
- }
- }
- $heredocExample = new heredocExample();
- $name = ‘Gunjan’;
- echo <<<ECO
- My name is “$name”. I am printing some $heredocExample->demo example.
- Now, I am printing {$heredocExample->example[1]}.
- It will print a capital ‘A’: \x41
- ECO;
- ?>
Output:
The output of the above program will be like:
My name is "$name". I am printing some $heredocExample->demo example. Now, I am printing {$heredocExample->example[1]}. It will print a capital 'A': \x41
Leave a Reply