HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Basic Syntax

Every programming language has a set of rules that define how to write and structure code. These rules are called **Syntax**. PHP's syntax is heavily inspired by C, Java, and Perl, making it very intuitive for developers coming from those backgrounds.


1. The PHP Tags

A PHP script can be placed anywhere in the document. A PHP script starts with <?php and ends with ?>. Anything inside these tags is processed by the server, while anything outside is sent directly to the browser as plain text or HTML.

<?php
    // Your PHP code goes here
    echo "This is processed by the server.";
?>
Note: You can have multiple PHP blocks in a single file. You can even open a PHP tag, start a loop, close the tag to write some HTML, and then open another PHP tag to close the loop later!

2. Case Sensitivity

In PHP, there is a very important distinction regarding case sensitivity. You must remember these two rules:

A. Keywords and Functions are NOT Case-Sensitive

Built-in keywords (like if, else, echo) and functions (like strtoupper()) are **not** case-sensitive. You can write them in uppercase, lowercase, or mixed case.

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

B. Variable names ARE Case-Sensitive

Unlike keywords, variable names are **strictly case-sensitive**. This means $color, $Color, and $COLOR are three completely different variables.

<?php
    $color = "red";
    echo "My car is " . $color; // Outputs: red
    echo "My house is " . $Color; // Error: $Color is undefined
?>

3. Mandatory Semicolons

In PHP, every statement must end with a semicolon (;). The semicolon tells the PHP engine that one instruction is finished and the next one is about to begin.

<?php
    $x = 10; // Semicolon required
    $y = 20; // Semicolon required
    echo $x + $y; // Semicolon required
?>
Common Error: Forgetting a semicolon is the #1 cause of "Parse error: syntax error, unexpected token" in PHP. Always double-check your line endings!

4. Handling Whitespace

PHP is generally indifferent to extra whitespace (spaces, tabs, newlines). This allows you to format your code in a way that is readable for humans.

<?php
    // Both do exactly the same thing
    echo "Compact style";

    echo 
        "Spaced 
        style";
?>
Pro Tip: Even though PHP doesn't care about whitespace, you should use consistent indentation (usually 4 spaces) to make your code professional and easy to debug.

Key Points to Remember

  • PHP tags: Code must be wrapped in <?php ... ?>.
  • Keywords: echo, IF, and while are not case-sensitive.
  • Variables: $name and $Name are different variables.
  • Semicolons: Every PHP statement must end with ;.
  • Files: PHP files should be saved with a .php extension to be processed by the server.