PHP Syntax Overview

PHP scripts are enclosed within <?php and ?> tags. Anything between these tags is interpreted as PHP code. Here's a simple example:

<?php
echo "Hello, World!";
?>

In this example, the echo statement outputs the string "Hello, World!" to the browser. This is one of the most commonly used functions in PHP for displaying data.

Variables

In PHP, variables start with a $ symbol followed by the variable name. PHP is a dynamically typed language, meaning you don't need to declare the data type of a variable explicitly. Here's how you can declare and use variables:

<?php
$greeting = "Hello";
$name = "Alice";
echo $greeting . ", " . $name . "!";
?>

This script will output: Hello, Alice!.

Data Types

PHP supports several data types, including:

TypeDescription
IntegerWhole numbers (e.g., 123)
FloatDecimal numbers (e.g., 3.14)
StringTextual data (e.g., "Hello")
BooleanTrue or false values
ArrayA collection of values
ObjectInstances of classes
NULLRepresents no value

Here's an example using different data types:

<?php
$age = 25;              // Integer
$price = 19.99;         // Float
$message = "Welcome";  // String
$isActive = true;       // Boolean
$fruits = array("apple", "banana"); // Array
?>

Control Structures

Control structures allow you to manage the flow of your program. The most common ones are if, else, elseif, and loops such as for, while, and foreach.

Conditional Statements

<?php
$score = 85;

if ($score >= 90) {
    echo "A";
} elseif ($score >= 80) {
    echo "B";
} else {
    echo "C";
}
?>

This script checks the value of $score and outputs a corresponding grade.

Loops

<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Number: " . $i . "<br>";
}
?>

This for loop prints numbers from 1 to 5.

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("Bob");
?>

This function greet() takes a parameter $name and returns a greeting string.

Learn more with official resources