PHP Basic Tutorial
Variables are used to store data that can be manipulated and retrieved during the execution of a script. Variables in PHP are easy to use, dynamically typed (meaning that you do not need to declare their type explicitly), and essential for creating dynamic, interactive web applications.
$
) followed by the variable name._
) but cannot start with a number.A-Z
, a-z
, 0-9
, and _
).$variable
and $Variable
are different).Try it yourself
In the example above, the variable $x
will hold the value 5
, and the variable $y
will hold the value "Hello, World!"
.
Note
When you assign a text value to a variable, put quotes around the value.
PHP has no command for declaring a variable, and the data type depends on the value of the variable.
Data type |
Description |
Example |
---|---|---|
String |
Stores a person's full name as a string. |
$name = "John Doe"; |
Integer |
Stores the age of a person as an integer. |
$age = 30; |
Double |
Stores a salary amount as a floating-point number. |
$salary = $5000.50; |
Boolean |
Indicates whether the person is employed (Boolean: true/false). |
$isEmployed = True; |
Array |
Store multiple values in a single variable |
$array = [1, "apple", true]; |
Object |
Store and manipulate complex data structures with properties (variables) and methods (functions) |
$p1 = new Person("Alice", 28); |
NULL |
It represents the absence of a value |
$var = null; |
Try it yourself
You can display the value of a variable using echo
or print
.
Try it yourself
strict
and non-strict
requirements, and data type declarations in the PHP Functions chapter.The gettype()
function in PHP is used to get the type of a variable. It returns the data type of the specified variable as a string. This can be helpful for debugging and for checking variable types dynamically.
Try it yourself
The var_dump()
function in PHP is used to display structured information (including the data type and value) about one or more variables. It is a powerful debugging tool that provides detailed insight into the contents of variables, making it helpful for developers to understand complex data structures.
How var_dump()
Works?
The var_dump()
function prints out:
Try it yourself
You can assign the same value to multiple variables in one line:
Try it yourself