Variables are used to store data like strings or numbers for example min_age=18. The value of the variable can be changed numerous times throughout the code. It is so easy to define variables in PHP just write $sign and then a variable name like this $min_age=18. You do not even need to mention the data type of variable. Because PHP will automatically choose the correct data type of variable according to the value stored in a variable.
PHP is a Loosely Typed language: –
PHP is a programming language known for its loose typing. This means that in PHP, variables can easily switch between different data types without needing explicit type declarations. While this flexibility can lead to some unexpected issues, it also allows developers to work quickly and creatively, making PHP a popular choice for web development, whether you’re building an e-commerce website or a content management system.
Declaring a Variable: –
Declaring a variable means announcing its existence and specifying its data type. When you declare a variable, you are telling the computer that you intend to use a specific name for a storage location in memory.
Initializing a Variable: –
Initializing a variable means giving it an initial value at the time of declaration or later in your code. It’s the act of assigning the first value to a declared variable. If you declare a variable but do not initialize it, its value will typically be undefined or garbage (contains whatever was in that memory location previously).
Basic Things to keep in mind while creating Variables in PHP: –
- All variables in PHP start with a $ sign, followed by the name of the variable.
- A variable name must start with a letter or the underscore character _.
- The variable name cannot start with a number.
- Variable names in PHP can only contain alpha-numeric characters and underscores (A-Z, 0-9, and _).
- The variable name cannot contain spaces.
To initialize a variable you just need the assignment operator (=) then write the value of the variable for example $min_age=18 or $name= ”Mohit”.
Now we will check this basic example to understand Variables in PHP.
<?php $age=22; $name="Mohit"; $city="Delhi"; $height=5.9; echo "Hello $name your age is $age. Your height is $height and You are from $city."; ?>
The output of the above-written code will be this: “Hello Mohit Your age is 22. Your height is 5.9 and You are from Delhi“.
I hope now you would have a clear idea about how to declare and initialize variables in PHP. Please continue with the next tutorials of this series.