The Variables In PHP

One of the basic elements of any programming language (including PHP ) are certainly the variables .

What is a variable?

The variable can be defined as a memory area in which information is saved (to which the programmer assigns a particular identifier) ​​which can change during the processing phase of the program itself.

In PHP all variables start with a dollar sign ( $ ). The value of a variable is assigned with an “equal” ( = ).

String Variables

Let’s see an example of a text variable (more correctly defined as a string variable:

//String Variable Syntax
$variable = "String Here..";

//Example
$name = "Mr, Jon";

Numeric Variables

If your variable, on the other hand, had a numeric value (so-called numeric variables ). The quotation marks would not be necessary; here is an example:

//String Variable Syntax
$variable = 123;

//Example
$age = 25;
$pi = 3.14;

Boolean Variables

Another type of variable widely used is the Boolean variable. We say “boolean” a variable that can have only “true” ( true ) or “false” ( false ) as its value:

// variable booleana if value true
$variabile = true;

// variable booleana if value false
$variabile = false;

Print the Value of a Variable on The Screen

Through the variables, we can perform various operations such as for example, mathematical calculations or comparisons. The simplest thing we can do with a variable is to print its content on the screen (obviously this operation does not make sense for Boolean type variables).

So let’s see a simple PHP code that uses variables and the echo command to print the value of a variable on the screen:

<?php
$name = "Mr. Joy";
echo $name;
?>

Warning : the variable names are case sensitive … therefore pay attention to upper and lower case!

Let’s take another example:

<?php
$name = "Mr. Joy";
$age = 25;
echo "Name: ". $name;
echo " Age: ". $age;
?>

In the latter example we have printed a sentence on the screen inside which there are two variables.

String concatenation

In the example above, we used two variables and printed them on the screen within a sentence. As you may have noticed, we used the dot ( . ) To join the different parts of the sentence together. The dot, in fact, is used in PHP as a concatenation operator.

<?php
$var1 = "Hello";
$var2 = "World!";
echo $var1 . $var2;
?>

It is hardly necessary to underline how, in the example above, the contents of the variables will be printed on the screen without any space. If we had wanted to add a space between one variable and another we would have had to write:

<?php
$var1 = "Hello";
$var2 = "World!";
echo $var1 . " " . $var2;
?>

A particular case is when you want to change the value of a variable using the concatenation operator.

Leave a Comment