Variables In PHP
This post describes PHP Variables in a way that is in compliance with educational standards.
A variable can be thought of as a “container” for storing information.
PHP Variables can be named in two ways: short and descriptive (example a and b), and long and descriptive (example: name, greeting, area_surface).
A variable in PHP is created by starting with a $ sign, followed by the variable’s name.
As a result of executing the above statements, the variable will be:
$name holds the value of Bill Gates!, $a holds the value of 3, And variable $b holds the value of 6.2.
Remember: Put quotes around text values when assigning them to variables.
IMPORTANT: PHP does not have a command for declaring variables. As soon as you assign a value to it, it is created.
A variable is a container for storing data.
PHP Variable Output
To display data on a screen, PHP echo is often used.
Below is an example showing how to display text and a variable:
Similar to the above example, this example will produce the following output:
Here is a simple example that sums two variables:
The example above demonstrates that PHP did not require us to specify the variable’s data type.
Depending on the variable’s value, PHP automatically assigns a data type.
It is possible to add a string to an integer without causing an error because the data types are not strictly defined.
Type declarations were added to PHP 7. If a type mismatch occurs when declaring a function, the strict requirement will throw a “Fatal Error”.
Remember: In the next chapter, you’ll learn more about how to output data to the screen using the echo statement.
PHP Variables Key Points
When declaring a variable in PHP, remember the following key points:
- Variable names begin with the $ sign, followed by the variable name.
- There must be a letter or underscore at the beginning of a variable name.
- Variable names cannot begin with a number.
- There can be only alphanumeric characters and underscores in variable names (A-z, 0-9, and _).
- It is recommended to use descriptive and meaningful names for variables to improve code readability and maintainability.
- The names of variables are case-sensitive ($name and $NAME are two different variables).
- Variables are assigned values using the “=” operator.
- The value of a variable can be changed throughout the program by reassigning it a new value.
- PHP is a dynamically-typed language, which means that the data type of a PHP variable can change automatically based on the value it is assigned. This is known as type juggling and can sometimes lead to unexpected results if not handled properly.