Variables in PHP start with a dollar sign ($) followed by the name of the variable.
A variable name
$abc = 12;
To check if a variable is defined, we can use (isset($name))
There are 8 variable types in PHP, and you don’t have to declare variable types when creating a variable.
$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
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>';
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>";
?>
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>";
?>