Variables in PHP



In programming languages, variables are the placeholders where you can store values.

These values include numbers, texts and more complex types like arrays and objects.

Variables are identified by a name. In PHP, variable names always start with a Dollar sign: $.

For example:

The variable name is $apples (note the $ at the beginning), and its value is the number 6.

The previous code snippet shows the syntax to assign a value to a variable:

  • variable name
  • equal sign "="
  • value

Like for any PHP statement, you must end the value assignment with a semicolon ;




You can assign a new value to a variable at any time.

At any point in your code, the variable will contain the last value assigned to it.

For example, in the following code snippet $apples is set to 6 and holds that value until you assign it a new value, 3.

After that, $apples will hold the value 3.

(Quick note: the text between /* and */ are comments. They are not part of the code. Their purpose is to explain what the code does.)


You can also use a variable as the value for another variable.

Like this:


Note that this does not mean that $bananas and $fruits become the same variable.

The value assignment only takes the current value of $bananas and assigns it to $fruits.

The two variables are still independent. If you change one of them after the assignment, the other one will not be affected.

Let's see what happens when you change the two variables:

Here is what happens at each step:

  1. $bananas has the value 5.
  2. $fruits gets the value from $bananas, so $fruits too has the value 5.
  3. Then, $bananas gets the value 3. $fruits does not change and still has the value 5.
  4. Then, $fruits gets the value 10. $bananas does not change and still has the value 3.
  5. Finally, $bananas gets the value from $fruits. So, at this point, both have the value 10.




So, this is how variables work in PHP.

Of course, you can do much more with them other than give them a value. But let's take one step at a time.

In the next lesson you will learn how to output variables using the echo PHP command.


Lesson recap.

  • PHP variable names always start with the Dollar sign ($).
  • You can set the value of a variable directly, or give them the value from another variable.
  • You can change the value of a variable at any time. At any point in your code, the variable holds the last value that has been assigned to it.




Complete and Continue  
Discussion

2 comments