In this tutorial, you’ll learn about the fundamental syntax of PHP, including opening and closing tags, comments, variables, echo statements, and the basic structure of PHP code.
PHP Basic Syntax
1. PHP Opening and Closing Tags
PHP code is embedded within HTML using PHP tags. The basic PHP opening tag is <?php
, and the closing tag is ?>
.
<?php
// Your PHP code here
?>
All PHP code must be placed within these tags to execute properly.
2. Comments in PHP
Comments are used to explain code and are ignored during execution. PHP supports single-line and multi-line comments.
// Single-line comment
# Another way to write single-line comments
/*
Multi-line comment
spanning multiple lines
*/
3. Echo and Print Statements
echo
and print
are used to output text to the screen. While echo
can take multiple parameters, print
behaves as a function that returns a value.
<?php
echo "Hello, World!";
print "Hello, PHP!";
?>
4. PHP Variables
Variables in PHP start with a $
sign, followed by the variable name. Variable names must begin with a letter or underscore and cannot contain spaces.
<?php
$variableName = "Value";
$number = 10;
?>
PHP is a loosely typed language, so you don't have to declare the data type of a variable.
5. PHP Data Types
PHP supports several data types, including:
- String: A sequence of characters. E.g.,
"Hello"
- Integer: Non-decimal numbers. E.g.,
123
- Float: Decimal numbers. E.g.,
3.14
- Boolean: True or False values.
- Array: An indexed collection of values.
- Object: Instances of classes.
6. Basic Operators in PHP
PHP provides various operators to perform operations:
- Arithmetic Operators:
+
,-
,*
,/
,%
- Assignment Operators:
=
,+=
,-=
, etc. - Comparison Operators:
==
,!=
,===
,!==
- Logical Operators:
&&
,||
,!
Operators help you perform calculations and comparisons within your code.
7. PHP Basic Syntax Example
Here’s a simple example that combines these basic PHP syntax elements:
<?php
// Declare a variable
$name = "John Doe";
// Output a greeting message
echo "Hello, " . $name . "!";
// Perform a calculation
$sum = 5 + 10;
echo "The sum is: " . $sum;
?>
8. Conclusion
Understanding the basic syntax of PHP is essential for further learning. With these foundational elements, you’re ready to explore more advanced PHP concepts.
Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.