Skip to content

Basic Syntax

Overview

Understanding PHP's syntax is essential for writing clean, readable, and maintainable code. This chapter covers the fundamental syntax rules, conventions, and best practices that every PHP developer should know.

PHP Opening and Closing Tags

Standard PHP Tags

php
<?php
// PHP code goes here
?>

Mixing HTML and PHP

php
<!DOCTYPE html>
<html>
<body>
    <h1><?php echo "Welcome to PHP!"; ?></h1>
    <p>Today is <?php echo date('Y-m-d'); ?></p>
</body>
</html>

Short Echo Tags (PHP 5.4+)

php
<h1><?= $title ?></h1>
<!-- Equivalent to: -->
<h1><?php echo $title; ?></h1>

Important Notes

  • Always use <?php tags (avoid short tags <?)
  • The closing ?> tag is optional at the end of PHP-only files
  • No whitespace before opening tag in PHP-only files

Statements and Expressions

Statements

Every PHP statement must end with a semicolon:

php
<?php
echo "Hello, World!";        // Statement
$name = "John";              // Statement
$result = 5 + 3;             // Statement
?>

Expressions

Expressions evaluate to a value:

php
<?php
$a = 5;                      // 5 is an expression
$b = $a + 3;                 // $a + 3 is an expression
$c = ($a > $b) ? $a : $b;    // Ternary expression
?>

Case Sensitivity Rules

Case-Sensitive Elements

php
<?php
// Variables are case-sensitive
$name = "John";
$Name = "Jane";      // Different variable
$NAME = "Bob";       // Different variable

// Class names are case-sensitive
class MyClass {}
$obj1 = new MyClass();    // Correct
// $obj2 = new myclass(); // Error
?>

Case-Insensitive Elements

php
<?php
// Function names are case-insensitive
function myFunction() {
    return "Hello";
}

echo myFunction();    // Works
echo MyFunction();    // Also works
echo MYFUNCTION();    // Also works

// Keywords are case-insensitive
IF (true) {           // Works (but not recommended)
    ECHO "Hello";     // Works (but not recommended)
}
?>

Comments

Single-Line Comments

php
<?php
// This is a single-line comment
echo "Hello"; // End-of-line comment

# This is also a single-line comment (Unix style)
$name = "John"; # Another comment
?>

Multi-Line Comments

php
<?php
/*
This is a multi-line comment
It can span multiple lines
Used for longer explanations
*/

$result = 5 * 3; /* Inline multi-line comment */
?>

Documentation Comments (PHPDoc)

php
<?php
/**
 * Calculates the area of a rectangle
 * 
 * @param float $width  Width of the rectangle
 * @param float $height Height of the rectangle
 * @return float Area of the rectangle
 */
function calculateArea($width, $height) {
    return $width * $height;
}
?>

Variables

Variable Declaration and Naming

php
<?php
// Valid variable names
$name = "John";
$_age = 25;
$firstName = "Jane";
$user_id = 123;
$isActive = true;
$HTML = "<h1>Title</h1>";

// Invalid variable names (will cause errors)
// $2name = "Error";     // Cannot start with number
// $first-name = "Error"; // Cannot contain hyphen
// $class = "Error";      // 'class' is a reserved word
?>

Variable Variables

php
<?php
$var = "name";
$name = "John";

echo $$var; // Output: John (equivalent to $name)

// More complex example
$prefix = "user_";
$user_name = "Alice";
$user_age = 30;

$field = "name";
echo ${$prefix . $field}; // Output: Alice
?>

Variable Scope

php
<?php
$globalVar = "I'm global";

function testScope() {
    $localVar = "I'm local";
    
    // Access global variable
    global $globalVar;
    echo $globalVar;
    
    // Or use $GLOBALS superglobal
    echo $GLOBALS['globalVar'];
}

// Static variables
function counter() {
    static $count = 0;
    $count++;
    echo $count;
}

counter(); // 1
counter(); // 2
counter(); // 3
?>

Constants

Defining Constants

php
<?php
// Using define() function
define("SITE_NAME", "My Website");
define("MAX_USERS", 100);
define("PI", 3.14159);

// Using const keyword (PHP 5.3+)
const APP_VERSION = "1.0.0";
const DEBUG_MODE = true;

echo SITE_NAME;    // My Website
echo MAX_USERS;    // 100
?>

Magic Constants

php
<?php
echo __FILE__;     // Full path of current file
echo __DIR__;      // Directory of current file
echo __LINE__;     // Current line number
echo __FUNCTION__; // Current function name
echo __CLASS__;    // Current class name
echo __METHOD__;   // Current method name
echo __NAMESPACE__; // Current namespace
?>

Class Constants

php
<?php
class MathConstants {
    const PI = 3.14159;
    const E = 2.71828;
    
    public function getCircumference($radius) {
        return 2 * self::PI * $radius;
    }
}

echo MathConstants::PI; // 3.14159
?>

Operators

Arithmetic Operators

php
<?php
$a = 10;
$b = 3;

echo $a + $b;  // 13 (addition)
echo $a - $b;  // 7  (subtraction)
echo $a * $b;  // 30 (multiplication)
echo $a / $b;  // 3.333... (division)
echo $a % $b;  // 1  (modulus)
echo $a ** $b; // 1000 (exponentiation, PHP 5.6+)
?>

Assignment Operators

php
<?php
$x = 10;        // Basic assignment
$x += 5;        // $x = $x + 5 (15)
$x -= 3;        // $x = $x - 3 (12)
$x *= 2;        // $x = $x * 2 (24)
$x /= 4;        // $x = $x / 4 (6)
$x %= 5;        // $x = $x % 5 (1)

$str = "Hello";
$str .= " World"; // String concatenation assignment
echo $str;        // "Hello World"
?>

Comparison Operators

php
<?php
$a = 5;
$b = "5";

var_dump($a == $b);  // true (equal value)
var_dump($a === $b); // false (identical - same value and type)
var_dump($a != $b);  // false (not equal)
var_dump($a !== $b); // true (not identical)
var_dump($a < 10);   // true (less than)
var_dump($a > 3);    // true (greater than)
var_dump($a <= 5);   // true (less than or equal)
var_dump($a >= 5);   // true (greater than or equal)
?>

Logical Operators

php
<?php
$x = true;
$y = false;

var_dump($x && $y);  // false (AND)
var_dump($x || $y);  // true (OR)
var_dump(!$x);       // false (NOT)
var_dump($x and $y); // false (AND - lower precedence)
var_dump($x or $y);  // true (OR - lower precedence)
var_dump($x xor $y); // true (XOR - exclusive or)
?>

Increment/Decrement Operators

php
<?php
$i = 5;

echo ++$i; // 6 (pre-increment)
echo $i++; // 6 (post-increment, then $i becomes 7)
echo --$i; // 6 (pre-decrement)
echo $i--; // 6 (post-decrement, then $i becomes 5)
?>

String Operators

php
<?php
$first = "Hello";
$second = "World";

$result = $first . " " . $second; // Concatenation
echo $result; // "Hello World"

$first .= " " . $second; // Concatenation assignment
echo $first; // "Hello World"
?>

Control Structures Syntax

If-Else Statements

php
<?php
$score = 85;

if ($score >= 90) {
    $grade = "A";
} elseif ($score >= 80) {
    $grade = "B";
} elseif ($score >= 70) {
    $grade = "C";
} else {
    $grade = "F";
}

// Ternary operator
$status = ($score >= 60) ? "Pass" : "Fail";

// Null coalescing operator (PHP 7+)
$username = $_GET['user'] ?? 'guest';
?>

Alternative Syntax

php
<?php if ($condition): ?>
    <p>This is displayed if condition is true</p>
<?php else: ?>
    <p>This is displayed if condition is false</p>
<?php endif; ?>

String Syntax

Single vs Double Quotes

php
<?php
$name = "John";

// Single quotes - literal string
$message1 = 'Hello, $name!';        // "Hello, $name!"
$message2 = 'It\'s a nice day';     // Escape single quote

// Double quotes - variable interpolation
$message3 = "Hello, $name!";        // "Hello, John!"
$message4 = "He said \"Hello\"";    // Escape double quote
?>

Heredoc Syntax

php
<?php
$name = "John";
$html = <<<HTML
<div class="user">
    <h2>Welcome, $name!</h2>
    <p>This is a heredoc string.</p>
</div>
HTML;

echo $html;
?>

Nowdoc Syntax (PHP 5.3+)

php
<?php
$text = <<<'TEXT'
This is a nowdoc string.
Variables like $name are not interpolated.
It's like single quotes but for multi-line strings.
TEXT;

echo $text;
?>

Array Syntax

Array Declaration

php
<?php
// Old syntax
$fruits1 = array("apple", "banana", "orange");

// New syntax (PHP 5.4+)
$fruits2 = ["apple", "banana", "orange"];

// Associative array
$person = [
    "name" => "John",
    "age" => 30,
    "city" => "New York"
];

// Mixed array
$mixed = [
    0 => "first",
    "key" => "value",
    1 => "second"
];
?>

Function Syntax

Function Declaration

php
<?php
// Basic function
function greet($name) {
    return "Hello, " . $name;
}

// Function with default parameters
function createUser($name, $role = "user", $active = true) {
    return [
        "name" => $name,
        "role" => $role,
        "active" => $active
    ];
}

// Function with type hints (PHP 7+)
function add(int $a, int $b): int {
    return $a + $b;
}

// Variable function
$functionName = "greet";
echo $functionName("John"); // Calls greet("John")
?>

Coding Standards and Best Practices

PSR-1 Basic Coding Standard

php
<?php
// File should start with <?php tag
// No closing ?> tag in PHP-only files

namespace MyProject\Models;

use DateTime;
use Exception;

class UserModel
{
    const STATUS_ACTIVE = 1;
    
    public $name;
    private $email;
    
    public function getName()
    {
        return $this->name;
    }
    
    public function setEmail($email)
    {
        $this->email = $email;
    }
}
?>

Naming Conventions

php
<?php
// Variables and functions: camelCase
$userName = "john_doe";
$isActive = true;

function getUserById($id) {
    // Function body
}

// Constants: UPPER_CASE
const MAX_LOGIN_ATTEMPTS = 3;
define('API_VERSION', '1.0');

// Classes: PascalCase
class UserController {
    // Class body
}

// Private/protected properties: prefix with underscore (optional)
class MyClass {
    private $_privateProperty;
    protected $_protectedProperty;
    public $publicProperty;
}
?>

Code Formatting

php
<?php
// Proper indentation (4 spaces recommended)
if ($condition) {
    if ($anotherCondition) {
        doSomething();
    }
}

// Proper spacing
$result = $a + $b * $c;
$array = ['item1', 'item2', 'item3'];

// Line length (80-120 characters max)
$longVariableName = someFunction($parameter1, $parameter2, 
                                $parameter3, $parameter4);
?>

Error Handling Syntax

Try-Catch Blocks

php
<?php
try {
    $result = riskyOperation();
    echo $result;
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
} finally {
    // Cleanup code (PHP 5.5+)
    cleanup();
}
?>

Next Steps

Now that you understand PHP's basic syntax, let's explore how PHP programs are structured in Program Structure.

Practice Exercises

  1. Create variables using different naming conventions and test case sensitivity
  2. Write a script using all types of operators
  3. Practice string interpolation with single quotes, double quotes, and heredoc
  4. Create functions with different parameter types and return values
  5. Write code following PSR-1 standards

Understanding these syntax fundamentals will make the rest of your PHP journey much smoother!

Content is for learning and research only.