PHP Variables
I. Variable in PHP
Variables in PHP start with a dollar sign ($) followed by the name of the variable.
A variable name
- must start with a letter or the underscore character.
- can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
- is case-sensitive ($name and $NAME are two different variables).
$abc = 12;
To check if a variable is defined, we can use (isset($name))
II. Variable types
There are 8 variable types in PHP, and you don’t have to declare variable types when creating a variable.
- String
- Integer
- Float
- Boolean
- Null
- Array
- Object
- Resource
$name = "Anna";
$age = 30;
$isFemale = true;
$height = 1.6;
$salary = null;
To display a structure of a variable including its type and value, we use var_dump().
// Print the whole variable
var_dump($name, $age, $isMale, $height, $salary);
// Result: string(4) "Anna" int(30) bool(true) float(1.600000000000000088817841970012523233890533447265625) NULL
III. Check variable types
To check type of a variable, we use gettype().
echo gettype($name) . '<br>';
Example
// Print types of the variables
echo gettype($name) . '<br>';
echo gettype($age) . '<br>';
echo gettype($isFemale) . '<br>';
echo gettype($height) . '<br>';
echo gettype($salary) . '<br>';
IV. Variable scopes
1. Global scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
<?php
$x = 5; // global scope
function count() {
// using x inside this function will generate an error
echo "<p>Variable x is: $x</p>";
}
count();
echo "<p>Variable x is: $x</p>";
?>
2. Local scope
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
<?php
function count() {
$x = 5; // local scope
echo "<p>Variable x is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x is: $x</p>";
?>