PHP Variables

In PHP, variables are used to store data that can be used and manipulated throughout a script. Here’s a quick guide to PHP variables:

1. Basic Syntax

  • All variables start with a dollar sign ($) followed by the variable name.

  • Variable names are case-sensitive ($name and $Name are different).

  • A variable name must start with a letter or underscore, followed by letters, numbers, or underscores.

<?php $name = "John"; $age = 25; $is_student = true; ?>

2. Variable Types

PHP is a loosely typed language, so you don’t have to declare data types. PHP automatically converts the variable to the correct data type.

Examples:

$string = "Hello"; // String $number = 100; // Integer $price = 99.99; // Float $is_active = true; // Boolean $array = [1, 2, 3]; // Array

3. Variable Scope

  • Local: Declared inside a function and accessible only within that function.

  • Global: Declared outside all functions and accessible using the global keyword inside functions.

  • Static: Preserves a variable's value after a function ends.

  • Superglobals: Built-in variables like $_POST, $_GET, $_SERVER.

Example of global:

$x = 10; function test() { global $x; echo $x; } test(); // Outputs 10

4. Variable Variables

You can dynamically create variable names using variable variables:

$foo = "bar"; $$foo = "baz"; echo $bar; // Outputs "baz"