PHP Syntax Reference

Complete guide to PHP syntax, examples, and best practices. Learn PHP step-by-step.

Introduction

PHP (Hypertext Preprocessor) is a server-side scripting language used for web development.

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

Variables

Variables store data and start with a $ sign:

<?php
$name = "Nahid";
$age = 25;
$isAdmin = true;
echo "Name: $name, Age: $age";
?>

Arrays

Arrays store multiple values:

<?php
$fruits = ["Apple","Banana","Mango"];
echo $fruits[0]; // Apple

$assoc = ["name" => "Nahid", "age" => 25];
echo $assoc["name"]; // Nahid
?>

Loops

PHP supports for, while, foreach:

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

$fruits = ["Apple","Banana","Mango"];
foreach($fruits as $fruit){
    echo $fruit." ";
}
?>

If / Else

<?php
$age = 20;
if($age >= 18){
    echo "Adult";
}else{
    echo "Minor";
}
?>

Switch

<?php
$day = "Monday";
switch($day){
    case "Monday":
        echo "Start of week";
        break;
    case "Friday":
        echo "Weekend coming";
        break;
    default:
        echo "Another day";
}
?>

Functions

<?php
function greet($name){
    return "Hello, $name";
}
echo greet("Nahid");
?>

Classes / OOP

<?php
class Person {
    public $name;
    function __construct($name){
        $this->name = $name;
    }
    function greet(){
        return "Hello ".$this->name;
    }
}
$p = new Person("Nahid");
echo $p->greet();
?>