PHP Variables

Learn about PHP variables, their usage, and best practices.

Introduction to PHP Variables

In PHP, variables are used to store data that can be used and manipulated throughout your script. Variables start with a dollar sign ($) followed by the variable name. The variable name must start with a letter or underscore, followed by any number of letters, numbers, or underscores.

Declaring Variables

<?php
$variableName = "value";
?>

Data Types

  • String: Text data (e.g., $name = "John Doe";)
  • Integer: Whole numbers (e.g., $age = 30;)
  • Float: Decimal numbers (e.g., $price = 19.99;)
  • Boolean: True or false (e.g., $isActive = true;)
  • Array: Collection of values (e.g., $colors = array("red", "green", "blue");)
  • Object: Instance of a class (e.g., $person = new Person("John");)
  • NULL: No value (e.g., $emptyVar = null;)

Variable Scope

PHP variables have different scopes:

  • Local: Variables declared inside a function or method.
  • Global: Variables declared outside functions. To access global variables inside a function, use the global keyword or the $GLOBALS superglobal array.

Variable Variables

PHP supports variable variables, where you can use the value of one variable as the name of another variable.

<?php
$name = "world";
$$name = "Hello, world!";
echo $world; // Outputs: Hello, world!
?>

Type Casting

You can explicitly convert variables to a different data type.

<?php
$number = "42";
$integer = (int)$number;
?>