PHP Variables
PHP Variables
Example
$x = 5;
$y = "John"
In the example above, the variable $x will hold the value 5, and the variable $y will hold the
value "John".
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is
created the moment you first assign a value to it.
Think of variables as containers for storing data.
PHP Variables
A variable can have a short name (like $x and $y) or a more descriptive name
($age, $carname, $total_volume).
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example
$txt = "W3Schools.com";
echo "I love $txt!";
The following example will produce the same output as the example above:
Example
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
Example
$x = 5;
$y = 4;
echo $x + $y;
Variable Types
PHP has no command for declaring a variable, and the data type depends on the value of the variable.
Example
$x = 5; // $x is an integer
$y = "John"; // $y is a string
echo $x;
echo $y;
Example
The var_dump() function returns the data type and the value:
$x = 5;
var_dump($x);
Example
See what var_dump() returns for other data types:
var_dump(5);
var_dump("John");
var_dump(3.14);
var_dump(true);
var_dump([2, 3, 56]);
var_dump(NULL);
Example
$x = "John";
echo $x;
Example
All three variables get the value "Fruit":
$x = $y = $z = "Fruit";