PHP Variables

Variables in PHP are used to store data, such as numbers, strings, or arrays. A variable starts with a $ sign, followed by the variable name.

1. Declaring Variables

PHP variables do not require explicit data types. The type is assigned automatically based on the value.

<?php
   $name = "John"; // String variable
   $age = 25; // Integer variable
   $price = 99.99; // Float variable
   $is_admin = true; // Boolean variable

   echo "Name: " . $name;
   echo "Age: " . $age;
?>

Try It Now

2. Variable Naming Rules

  • Must start with a $ sign.
  • Must begin with a letter or an underscore (_).
  • Cannot start with a number.
  • Can only contain letters, numbers, and underscores.
  • Variable names are case-sensitive ($name and $Name are different).

3. Concatenation

Use the dot (.) operator to join strings.

<?php
   $first_name = "John";
   $last_name = "Doe";

   echo "Full Name: " . $first_name . " " . $last_name;
?>

Try It Now

4. Variable Scope

PHP variables can have different scopes: local, global, and static.

Global Scope

Variables declared outside functions have a global scope.

<?php
   $globalVar = "I am global";

   function showVar() {
      global $globalVar;
         echo $globalVar;
   }

   showVar();
?>

Try It Now

Local Scope

Variables declared inside a function are local to that function.

<?php
   function localExample() {
      $localVar = "I am local";
      echo $localVar;
   }

   localExample();
   // echo $localVar; // This will cause an error
?>

Try It Now

Static Variables

Use static to retain a variable’s value between function calls.

<?php
     function counter() {
         static $count = 0;
         $count++;
         echo $count;
     }

     counter();
     counter();
     counter();
?>

Try It Now

5. Variable Variables

Variable variables allow you to use a variable’s value as a variable name.

<?php
     $varName = "hello";
     $$varName = "Hello, World!";

     echo $hello; // Outputs: Hello, World!
?>

Try It Now

Conclusion

PHP variables are flexible and easy to use. Understanding scope and naming rules will help you write better scripts.