Usually when programming languages are learned, the first lesson is how to declare a variable. Declaring variables in PHP is very easy. In this article, we will go through the basics of declaring a variable in PHP.

Table of Contents

But before we start with how to declare a variable in PHP, we need to explain what is a variable.

What is variable?

1-1

A variable represents storage location with an associated name that contains information otherwise known as value. A variable is a named container for a particular sets of bits or type of data. Usually a variable is associated with a memory address. 2-1-1024x883

Variables in PHP

The variables in PHP are defined by a dollar sign followed by the name of the variable. As with other labels in PHP, variable names follow the same rules. When declaring a variable it should start with a letter or underscore, followed by any number of letters, numbers or underscores. In the example below, are some examples of declaring variables.

<?php
$name = "John";
$surname = "Doe";

$first_name = "Julia";
$_1stname = "Vilma";

Another way to assign values to variable is through assigning by reference. Assign by reference means that the new variable references or points to the original variable. If there are any changes to the new variable that will affect the original and vice versa. In the example below, we tried to assign by reference, with prepending an ampersand(&) to the beginning of the value which is being assigned.

<?php
$fruit = "banana";
$secondfruit = &$fruit;

echo "First fruit: " . $fruit . "\n";
echo "Second fruit:  ". $secondfruit. "\n";

$secondfruit = "orange";

echo "First fruit: " . $fruit. "\n";
echo "Second fruit: " . $secondfruit. "\n";

From the example above, we can see that if we create a reference to the variable, and then try to change the value of the reference, the value of the first variable will be changed.

Variable Variables

Variable variables is a variable name which can be set and used dynamically. For example:

<?php
$sample = "lorem";
$$sample = "ipsum dolor";

echo "$sample ${$sample}". "\n";
echo "$sample $lorem" . "\n";

If you execute the code above in the terminal, you will notice that the two echo statements produce same output.

lorem ipsum dolor
lorem ipsum dolor

Predefined variables

When executing a PHP script there is a large number of predefined variable provided by PHP. These variables depend upon which server is running, the version and the setup of the server, and many other factors. For more details, please check the list of predefined variables in the official PHP documentation.

Conclusion

In this article, you got to explore how to declare variables and assigning by reference. Through examples you learned how to declare a variable and declaring variable variables. If you would like to learn more about variables you can check the official PHP documentation. Also the code of this tutorial is available on my Github.


php