Learn PHP - Learn PHP Variables Cheatsheet - Codecademy
Learn PHP - Learn PHP Variables Cheatsheet - Codecademy
PHP Variables
In PHP, variables are assigned values with the assignment
operator ( = ). $my_variable = "Hello";
Variable names can contain numbers, letters, and
underscores ( _ ). A sigil ( $ ) must always precede a $another_cool_variable = 25;
variable name. They cannot start with a number and they
cannot have spaces or any special characters.
The convention in PHP is to use snake case for variable
naming; this means that lowercase words are delimited
with an underscore character ( _ ). Variable names are
case-sensitive.
Parsing Variables within PHP Strings
In PHP, variables can be parsed within strings specified
with double quotes ( " ). $my_var = "cat";
This means that within the string, the computer will
replace an occurence of a variable with that variable’s echo "There is one $my_var on the mat";
value.
When additional valid identifier characters (ie. characters
/* If there were three cats, then you can
that could be included in a variable name) are intended to
type: */
appear adjacent to the variable’s value, the variable name
echo "There are three {$my_var}s on the
can be wrapped in curly braces {} , thus avoiding
confusion as to the variable’s name. mat ";
/* The curly braces help to avoid
confusion between the variable name and
the letter s, so PHP does not consider the
variable name as my_vars */
$var1 = "John";
echo $var1;
// var1 now holds the value "John"
echo $var1;
// Output: 8
$b = 7 / 3;
// The variable $b will hold a floating
point value, since the operation evaluates
to a decimal number.
$b = -19 % 4;
//The remainder of this operation is -3.
So the variable $b will hold the integer
value -3.
$c = 20 % 2;
//The remainder of this operation is 0. So
the variable $c will hold the integer
value 0.