TOC

The community is working on translating this tutorial into Italian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Basic PHP:

Variables

Variables are one of the most important aspects of every programming language. They allow you to store a value within a named container, for later use or manipulation. Storing and retrieving something from memory is a complicated task, but fortunately, PHP hides all this low level stuff, and makes it super easy to declare and use variables.

In PHP, variables can be recognized from the $ in front of them. The dollar sign is used to inform PHP that the following piece of text refers to a variable. If you have used other programming languages, you may be used to telling the compiler/interpreter which type of variable you wish to declare. However, PHP is a so-called loosely typed language. It means that you don't have to declare a variable as a specific type - it's type will be determined by what you put into it. We will talk more about this in the next chapter. For now, let's work with some variables.

In many other languages, you have to declare a variable before using it, usually with a specific keyword like "var", "dim" or at least the type you wish to use for the variable. But not so with PHP. Just enter the name of it and assign a value, and you're good to go. Here is an example:

<?php
$myVar = "Hello world!";
?>

Now that's pretty simple! You simply write the name of the variable with a dollar sign in front of it, an equal sign, and then you tell PHP what to put inside of the variable. Now, the variable called myVar holds the value of a text string - "Hello world!". Using the variable is even simpler. In this example, we use it with the echo function (it's actually just a language construct and not a function, but that doesn't matter now), which simply outputs it.

<?php
$myVar = "Hello world!";
echo $myVar;
?>

In this example, we used a text string, but we may as well use e.g. a number, like this:

<?php
$myVar = 42;
echo $myVar;
?>

On the other hand, why not just use a text string with the number 42 in it? That's no problem. Try putting quotes around the number in the above example, and you will see that you get the exact same output. But is it in fact the same? No, of course not. While PHP may not seem to care, internally it does, keeping track of the data types you put into your variables. You can read more about that in the chapters about data types.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!