First PHP Example
In this tutorial we will learn what is the syntax to write basic PHP code, how we can integrate PHP code in an HTML file and how to run the PHP script and check the output in the browser.
You must have XAMPP installed and running for the PHP script to work. If you have not installed XAMPP, go to the last tutorial and install XAMPP.
Hello World script in PHP
All the php code is written inside php code tags which is
?>. And the file with php code is saved with an extension
.php. Here is a simple example:
// code statements
Hence a simple Hello, World! program in PHP will be:
echo "Hello, World!";
echo is a command used in PHP to display anything on screen.
If we want to include this php code in an HTML document, we can do so like this:
echo "<h1>Hello, World!</h1>";
Now copy the above code and paste it in you Code Editor or IDE and save the file with the name hello_world.php
Now go to your C directory where XAMPP was installed, and open xampp → htdocs and create a new folder with name studytonight and put your php code file hello_world.php in the studytonight folder.
Now visit the following link in your browser: localhost/studytonight/hello_world.php and you would see Hello, World! written on the screen. Notice that Hello, World! is written as a heading because in the HTML code we specified that Hello, World! should be printed as a heading as put it inside the heading tag
PHP Syntax Rules
Below we have a listed down the main syntax rules that you must follow while writing php code.
- All the php code in a php script should be enclosed within
?>, else it will not be considered as php code. Adding php code inside the PHP tags is known as Escaping to php.
<?php ... ?>
Apart from the standard
?>, you can also use the Short-open tags:
<? ... ?>
<script language="PHP"> ... </script>
- Every expression in PHP ends with a semicolon
- Commenting PHP code: Both single line and multi-line comments are supported in PHP. For single line comment, we can either use
// before the comment line. For example,
# This is also a single line comment
# another line of comment
// This is a single line comment
echo "Example for Single line Comments";
And for multi-line comments, we use
/* ... */. For example,
This is also a single line comment
another line of comment
echo "Example for Multi-line Comments";
- PHP is case sensitive, which means that a variable
$tiger is not same as
$Tiger. Both of these, represent two different variables here.
But all the predefined keywords and functions like
echo etc are case insensitive.
echo "Hello, World!";
ECHO "Hello, World!";
- PHP uses curly braces to define a code block.
if($zero == 0)
echo "If condition satisfied";
echo "This is a code block";
Don't worry we will learn about
if...else conditions in details, this is just to demonstrate the use of curly braces.