Here you will learn about the basic syntax of PHP language, that is, how to write PHP code.
As you know, a PHP script is executed on the server, and then the plain HTML result is sent back to the browser.
You can place your PHP script, anywhere in an HTML document. All PHP script must start with <?php and ends with ?>. In other words all PHP script must be placed inside <?php and ?>. Here is the general form of a PHP script:
<?php // PHP code goes here ?>
And to run the PHP script or PHP code in your browser, you must have to save the file ending with .php extension, and if you save the file ending with other than .php, that is, if you save the file ending with .html or .htm then all the content along with <?php, echo, and ?> etc. will be printed in the browser.
Therefore after writing PHP code, when you save the code in file with any name, then must put .php at the end of that file.
Let's take an example to understand how PHP code can be written.
<html> <head> <title>PHP Basic Syntax - CodesCracker</title> </head> <body> <?php echo "<p>You can use echo to put anything as output.</p>"; echo "<p>This is the way to write any PHP code.</p>"; echo "<p>Save this file as codescracker.php</p>"; echo "<p>Open browser and type localhost/codescracker.php</p>"; ?> </body> </html>
Here is the output of the above PHP code, that will be produced in the browser.
Let's look at the following PHP Example:
<!DOCTYPE html> <html> <body> <h1>My first PHP page</h1> <?php echo "Hello PHP!"; ?> </body> </html>
It will produce the following result:
Note - PHP statement ends with a semicolon (;)
In PHP, all the keywords such as if, else, while, or echo, and classes, functions, or user-defined functions are not case-sensitive. Therefore, here in the below small PHP script, all the three echo statements are valid in PHP:
<!DOCTYPE html> <html> <body> <?php ECHO "Hello World!<br>"; echo "Hello Browser!<br>"; EcHo "Hello PHP!<br>"; ?> </body> </html>
Here is the output produced by the above PHP script:
However, in PHP, all the variable names are case-sensitive. Therefore, here in the below PHP example, only first statement will display the value of the variable named $color. This is because $color, $COLOR, and $coLOR are treated as three different variables.
<!DOCTYPE html> <html> <body> <?php $color = "blue"; echo "My car is " . $color . "<br>"; echo "My house is " . $COLOR . "<br>"; echo "My boat is " . $coLOR . "<br>"; ?> </body> </html>
Here is the output of the above PHP script:
© Copyright 2021. All Rights Reserved.