Basic PHP Syntax
PHP Tags
PHP code is embedded within HTML using special tags. The most common tag to start and end PHP code is <?php
and ?>
. This tells the server to process the code within these tags as PHP.
For example:
<?php
echo "Hello, PHP!";
?>
You can also use short tags like <?
and ?>
but be aware that short tags are not always enabled on all servers, so it’s best to stick with the full <?php
tags for compatibility.
Echoing Content
In PHP, you often want to display information to the user, and you do that using the echo
statement. The echo
statement outputs data to the screen. You can use echo
to print text, variables, or even HTML elements.
Here’s a simple example:
<?php
echo "Welcome to PHP!";
?>
This code will output: Welcome to PHP!
You can also use echo
to display variables or HTML:
<?php
$name = "John";
echo "Hello, $name!"; // Outputs: Hello, John!
echo "<br>"; // Outputs a line break in HTML
echo "<h1>PHP is awesome!</h1>"; // Outputs an HTML header
?>
Comments in PHP
Like most programming languages, PHP allows you to add comments in your code. Comments are important for explaining your code to others (or to yourself, months later). PHP supports both single-line comments and multi-line comments.
-
Single-line comments: Use
//
or#
for a single line of comment.
<?php
// This is a single-line comment
# This is another way to write a single-line comment
?>
-
Multi-line comments: Use
/*
to start the comment and*/
to end it.
<?php
/*
This is a multi-line comment.
You can write comments over multiple lines.
*/
?>
Summary of Basic PHP Syntax:
- PHP code starts with
<?php
and ends with?>
. - Use
echo
to output text or variables. - Add comments with
//
,#
, or/* */
for single-line or multi-line comments.