The Basic Rules of PHP

Every language has grammar rules, and PHP is no different. In this lesson, we'll cover the absolute fundamentals of PHP syntax. Mastering these simple rules is the key to writing code that works correctly.


1. The PHP Tags

All of your PHP code must be placed inside a special pair of tags. The server uses these tags to know which part of the file it needs to process as PHP code.

The opening tag is <?php and the closing tag is ?>.

<?php
    // All your PHP code must go in here!
?>

You can place these PHP blocks anywhere in an HTML document. A file containing PHP code must be saved with a .php extension.


2. Displaying Output with echo

The most common command you'll use in PHP is echo. Its job is simple: to output data to the browser. This data can be simple text, numbers, or even HTML tags.

<?php
    echo "Hello, this is my first PHP sentence!";
    echo "<br>"; // This will output an HTML line break tag
    echo "<h3>PHP can output HTML!</h3>";
?>

3. The Semicolon: The Most Important Character

Think of the semicolon ; as the period at the end of a sentence. In PHP, **every individual statement must end with a semicolon.** Forgetting it is one of the most common errors for beginners.

// CORRECT: Each line ends with a semicolon.
echo "Line one.";
echo "Line two.";

// INCORRECT: This will cause a syntax error.
// echo "Line one"
// echo "Line two";
?>

4. Comments: Leaving Notes in Your Code

Comments are lines in your code that PHP will completely ignore. They are not for the server; they are for you and other developers to read. Use them to explain what your code does.

<?php
    // This is a single-line comment.

    # This is also a single-line comment.
    
    /*
      This is a multi-line comment block.
      You can write as many lines
      as you want here.
    */
    
    echo "This line will be executed."; // Comments can also be at the end of a line.
?>

5. Case Sensitivity in PHP

It's important to know what is and isn't case-sensitive in PHP.

  • NOT Case-Sensitive: Keywords (like if, else, echo), function names, and class names. This means echo, ECHO, and eChO are all the same.
  • IS Case-Sensitive: Variable names. This is extremely important! The variable $name is completely different from $NAME.
<?php
    $color = "blue";
    
    echo "My favorite color is " . $color . ".<br>"; // Works
    echo "My favorite color is " . $COLOR . ".<br>"; // This will cause an error because $COLOR is not defined
    ECHO "This command works because 'echo' is not case-sensitive.";
?>

Now that you know the basic grammar, you're ready to learn about the building blocks of PHP programming: variables. We'll cover that in the next lesson!