In this tutorial, you shall learn about variables in PHP, rules for naming a variable, how to assign values to variables, and go through tutorials related to variables, with example programs.
Variables
In PHP, variables are used to store values like numbers, string, arrays, etc.
The syntax to declare a variable and assign a value to it is shown in the following.
$name = value;
where
name
is the variable name.value
is the value assigned to the variable.
We can access the value assigned to the variable using the variable name.
In the following example, we assign numbers to variables a
and b
, and access the values using the variable name in the third statement where we add the values in a
and b
, and assign the result to variable c
.
<?php
$a = 10;
$b = 20;
$c = $a + $b;
?>
Rules for naming a variable
We have to follow the below rules while naming a variable.
$
sign must be specified as prefix to the actual variable name. Example$age
.- Variable name must start with an alphabet or the underscore character. Examples:
$age
,$gender
,$_salary
. - Variable name can contain alpha numeric characters and underscore. Examples:
$name1
,$name2temp
,$name_temp
,$_name
. - Variable name cannot contain spaces.
PHP Tutorials on Variables
- PHP – Check if a variable is set PHP Tutorial to check if a given variable is set, using
isset()
function. - PHP – Get type of variable PHP Tutorial to get the type of variable using
gettype()
function. - PHP – Variable in string PHP Tutorial to write a variable in a string using curly braces.
Conclusion
In this PHP Tutorial, we learned how to define variables, and how to use access the values stored in them, with the help of examples.