PHP Syntax Explained
PHP (Hypertext Preprocessor) is a server-side scripting language used for web
development. It is embedded in HTML and executed on the server before sending the output
to the browser.
1. Basic PHP Syntax
Every PHP script starts with `<?php` and ends with `?>`.
Example:
<?php
echo "Hello, World!";
?>
2. Comments in PHP
PHP supports single-line and multi-line comments.
Examples:
// Single-line comment
# Another single-line comment
/* Multi-line comment */
3. Variables in PHP
Variables in PHP store data and start with a `$` symbol.
Example:
$name = "John";
$age = 25;
$price = 10.5;
4. Data Types in PHP
PHP supports various data types including integers, floats, strings, booleans, arrays, and
null values.
Example:
$integer = 100;
$float = 10.5;
$string = "Hello";
5. Conditional Statements in PHP
PHP supports conditional statements such as if, else, and switch.
Example:
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
6. Loops in PHP
Loops allow executing a block of code multiple times.
For Loop Example:
for ($i = 1; $i <= 5; $i++) {
echo "Number: " . $i . "<br>";
}
7. Functions in PHP
Functions help in organizing reusable blocks of code.
Example:
function greet($name) {
return "Hello, " . $name . "!";
}
echo greet("Alice");
8. Arrays in PHP
Arrays store multiple values in a single variable.
Example of Indexed Array:
$fruits = array("Apple", "Banana", "Orange");
echo $fruits[0];