PHP Basics


In PHP, a variable starts with the $ sign, followed by the name of the variable.

Rules for PHP variables:

  • A variable name must start with a letter or the underscore character.
  • A variable name cannot start with a number.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ($age and $AGE are two different variables)
    $name = "Jon Doe";
    $age = 21;
    $height = 1.85;
    $weight = 196;

<table width="90%" border="1">
    <td><?php echo $name; ?></td>
    <td><?php echo $age; ?></td>
    <td><?php echo $height; ?></td>
    <td><?php echo $weight; ?></td>


Variable Scope

PHP has three different variable scopes:

  • local
    A variable declared inside a function
  • global
    A variable declared outside a function
  • static
    A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope

    $global_count1 = 0;
    $global_count2 = 0;

    function sayHello($name) {
        $local_count = 0;
        static $static_count = 0;
        global $global_count2;


        echo "<p>Hello $name</p>";
        echo "<p>counts</p>";
        echo "<ul>";
        echo "<li>Global Count1: $global_count1</li>";
        echo "<li>Global Count2: $global_count2</li>";
        echo "<li>Local Count: $local_count</li>";
        echo "<li>Static Count: $static_count</li>";
        echo "</ul>";


    sayHello("Jon Doe");
    sayHello("Jane Doe");
    sayHello("Play Doe");

    echo "<p>Outside Function - name: $name</p>";


Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.