PHP Variable
PHP variable is a "container" that stores value and information. A variable starts with the $ sign, followed by the name of the variable.
PHP Variables: Basics
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
A variable can have a short name (like x and y or a and b) or a more descriptive name (name, age, description, multiple_hobbies).
As a regular expression, it would be expressed thus: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$
Note: A letter here is a-z, A-Z, and the bytes from 128 through 255 (0x80-0xff).
- A variable starts with the $ sign, followed by the name of the variable.
- A variable name must start with a letter or the underscore character.
- A variable name cannot start with a number.
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
- The variable name is case-sensitive. ($age and $AGE are two different variables)
PHP variable:
Think of variables something like containers that can store any value.
PHP Code:
php-variable.php
PHP Variable Examples
Source: solvprog.com
PHP Variable Output
Source: solvprog.com
Code: php-variable.php
<?php
$welcome_text = "Solvprog.com PHP Tutorial";
$x = 5;
$y = 10.5;
$name = 'Sagar';
$Name = 'Kalyan';
echo "Welcome to " . $welcome_text . "! - ";
// outputs "Welcome to Solvprog.com PHP Tutorial!";
echo $x + $y . " - ";
// outputs "15.5"
echo "$x + $y" . " - ";
// outputs "5 + 10.5"
echo "$name, $Name" . " ";
// outputs "Sagar, Kalyan"
?>
PHP is a Loosely Typed Language
In the example above, did you notice that we did not specified PHP variable which data type the variable is.
PHP automatically associates a data type to the variable, depending on its value.
In PHP 7, type declarations were added. This gives an option to specify the data type expected when declaring a function, and by enabling the strict requirement, it will throw a "Fatal Error" on a type mismatch.
You will learn more about strict and non-strict requirements, and data type declarations in the PHP Functions chapter.