PHP Variables

  • Variables are named storage spaces for data types. They act as identifiers to access memory locations.
  • A PHP variable name must start with a $ sign and consist only of alphanumeric characters and underscores, are case sensitive.
  • Variables are assigned with the = operator, with the variable name on the left-hand side and the value or expression to be stored on the right.
  • Variables can be re-assigned. The value of a variable is the value of its most recent assignment.
  • Variables can, but do not need to be declared before assignment. Variables used before they are assigned have default values.
  • Variables in PHP do not have intrinsic types and therefore none need to be declared before assignment. PHP automatically converts types from one to another as needed.

Data Types

Data Type Example Description
String $string = "hello"; A string is a sequence of characters.
Integer $integer = 23; An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Float $float = 23.916; A float (floating point number) is a number with a decimal point or a number in exponential form.
Boolean $bool = true; A Boolean represents one of two possible states: true or false.
Array $array = array('Volvo', 'BMW', 'Toyota'); An array stores multiple values in one single variable.
Object $my_car = new Car(); An object is an instance of a class. A class can store it’s own variables and functions (called methods).
NULL $null = null This data type which can have only one value: NULL. A variable of data type NULL is a variable that has no value assigned to it.

Type Casting

$num = "3.14";
$int = (int)$num;
$float = (float)$num;