PHP Syntax and Basics: A Comprehensive Guide
PHP Syntax Overview
PHP scripts are enclosed within <?php and ?> tags. These tags tell the server to interpret the enclosed code as PHP. While it's common to use <?php for opening tags, some developers may use the short tag <? for brevity, though this is not recommended due to potential compatibility issues.
<?php
echo "Hello, world!";
?>
In the example above, the echo statement outputs the string "Hello, world!" to the browser. This is one of the most common ways to display data in PHP.
Variables and Data Types
In PHP, variables start with a $ symbol followed by the variable name. PHP is a dynamically typed language, which means you don't need to declare the type of a variable explicitly.
<?php
$age = 25;
$name = "Alice";
$isStudent = true;
$gpa = 3.7;
?>
PHP supports several data types:
| Type | Description |
|---|---|
| Integer | Whole numbers (e.g., 42, -7) |
| Float | Decimal numbers (e.g., 3.14, -0.5) |
| String | Sequences of characters (e.g., "PHP") |
| Boolean | True or false values |
| Array | Collections of values |
| Object | Instances of classes |
| Null | Represents no value |
Control Structures
Control structures allow you to manage the flow of your program. PHP supports if-else, switch, for, while, and foreach loops.
Conditional Statements
<?php
$score = 85;
if ($score >= 90) {
echo "A";
} elseif ($score >= 80) {
echo "B";
} else {
echo "C";
}
?>
Loops
<?php
// For loop
for ($i = 1; $i <= 5; $i++) {
echo "Iteration $i<br>";
}
// While loop
$i = 1;
while ($i <= 5) {
echo "Iteration $i<br>";
$i++;
}
// Foreach loop
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
echo "$fruit<br>";
}
?>
Functions
Functions in PHP allow you to group code into reusable blocks. You can define your own functions using the function keyword.
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
?>
PHP also includes a wide range of built-in functions for tasks such as string manipulation, date handling, and file operations.
Arrays
Arrays in PHP can store multiple values in a single variable. They can be indexed or associative.
Indexed Arrays
<?php
$colors = ["red", "green", "blue"];
echo "First color: " . $colors[0];
?>
Associative Arrays
<?php
$student = [
"name" => "Alice",
"age" => 22,
"major" => "Computer Science"
];
echo "Student name: " . $student["name"];
?>