In this tutorial, you will learn about PHP Variables step by step. So without much to do, let’s get started.
Variables are “containers” for storing information.
In this tutorial, you will learn-
Creating (Declaring) PHP Variables
In PHP, a variable starts with the $ sign, followed through the name of the variable:
<!DOCTYPE html> <html> <body> <?php $txt = "Hello world!"; $x = 5; $y = 10.5; echo $txt; echo "<br>"; echo $x; echo "<br>"; echo $y; ?> </body> </html>
After the execution of the statements above, the variable $txt will hold the value Hello world!, the variable $x will hold the value 5, and the variable $y will keep the value 10.5.
Note: When you assign a text value to a variable, placed quotes across the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a cost to it.
Think of variables as containers for storing data.
A variable can have a short name (like x and y) or a extra descriptive call (age, carname, total_volume).
Rules for PHP variables:
• A variable starts with the $ sign, accompanied by the name of the variable
• A variable name ought to begin with a letter or the underscore character
• A variable name can not start with a number
• A variable call can simplest contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different variables)
Remember that PHP variable names are case-touchy!
The PHP echo statement is often used to output data to the display screen.
The following example will show how to output text and a variable:
<!DOCTYPE html> <html> <body> <?php $txt = "worldofitech.com"; echo "I love $txt!"; ?> </body> </html>
The following example will produce the same output as the example above:
<!DOCTYPE html> <html> <body> <?php $txt = "worldofitech.com"; echo "I love " . $txt . "!"; ?> </body> </html>
The following example will output the sum of variables:
<!DOCTYPE html> <html> <body> <?php $x = 5; $y = 4; echo $x + $y; ?> </body> </html>
Note: You will study more about the echo statement and how to output data to the display screen in the next chapter.
PHP is a Loosely Typed Language
In the example above, observe that we did no longer have to inform PHP which data type the variable is.
PHP automatically associates a data type to the variable, relying on its value. Since the data types aren’t set in a strict sense, you can do things like adding a string to an integer without causing an error.
In PHP 7, type declarations were added. This offers an option to specify the data type expected whilst declaring a characteristic, and through enabling the stern requirement, it will throw a “Fatal Error” on a type mismatch.
This is about PHP Variables, and we hope you have learned something from this tutorial and share your opinion about this tutorial. What do you think about it, and if you think this tutorial will help some of your friends, do share it with them.