What is Variable in PHP
PHP Variables are containers which are used to store data or information.
PHP Variable Declaration
In PHP All variable names must start with a $ sign, followed by the name of the variable. Like this –
You can declare variables anywhere in the PHP script.
Assign Value to a Variable
Use the = equal sign to assign value for a variable. Like this –
$name = "John Doe";
This = equal sign is called Assignment Operator.
<?php $name = "John Doe"; // Declaring a variable echo $name; // Displaying the variable value ?>
Naming Conventions of a Variable
To Declare or Create a PHP Variable you need to follow some Rules –
- Variable Must start with a $ sign.
- 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 to z, 0 to 9 and _ )
In PHP, variable names are case-sensitive. In the below example both are different variables –
$searchengine = "Google"; $searchEngine = "Yahoo";
PHP Data Types
You can assign all the data types in a variable, that are available in PHP.
Below, the list of the PHP Data Types with a short description –
1 – String – A string is a sequence of characters, that are inside a single or double quote.
$x = "Hello world";
2 – Integer – An integer is a non-decimal number.
$x = 123;
3 – Float – A float is a number with a decimal point.
$x = 10.5;
4 – Boolean – True or False.
$x = true;
5 – Array – Collection of multiple values.
$x = array("value1","value2");
6 – Object – An object is an instance of a class.
7 – NULL – If there is a NULL data type in a variable, then that means the variable does not have any value.
$x = NULL;
If a variable is declared without any value, then the variable is automatically assigned the NULL value.
8 – Resource – Such as Database Connection.
Previous is – PHP Introduction, Setup Dev Environment, Run PHP Code