Learning PHP – Lesson 2 – Learn the PHP variables
In the previous articles we have seen how to setup the PHP environment and how to use print and echo. If you have missed here is a group of links of articles of the same series
Other articles of the same series
If you really like this series of articles, please share and help us to grow.
In this one we are going to learn the PHP variables
What is a variable
A variable is a name of memory location and they are used for storing values that could be numeric, characters, etc. They are represented by the dollar sign $ followed by the name and those names are case-sensitive i.e. $hello is different from $Hello.
How PHP variables are defined
The PHP variables are defined starting from the $ sign followed by an underscore “_” or letter and any number. In other words can start only with _ or a letter and then any other alphanumeric character a-z,A-Z and numbers from 0 to 9 including the _. Few examples below
<?php
$a = 'valid';
$_a = 'still valid';
$3 = 'will generate an error';
$_3 = 'still valid'
$is_this_a_valid_variable_name = 'yes';
?>
How PHP variables are used
The PHP variables are used as they are defined, and by that I mean just referencing to them using the $ sign. See the example below
<?php
$hello = 'Hello world';
echo $hello;
?>
In the previous article we spoke about the difference between ‘ and ” now it’s time to understand what that means, see the example below
<?php
$first = "hello";
$second = "world";
// 1 - first example
echo "$first";
echo "\n";
echo "$second";
echo "\n";
// 2 - second example
//the above is the same of this
echo "$first\n$second\n";
// 3 - third example
//but is not the same of this
echo '$first';
echo '\n';
echo '$second';
echo '\n';
?>
As you can see in the third example the variables are not expanded and the output is written as it is, it’s really important to understand this concept as it can lead to potential malfunctioning of your applications.
The variables can also be combined
<?php
$name = "Bob";
$surname = "Hunt";
$fullName = "$name $surname"; // "Bob Hunt"
?>
Bonus section: Your first algorithm – The swap
The following example is going to swap the values between $var_1 and $var_2. The Idea is pretty easy is like having 2 buckets and you want to swap the content, all you need is a third bucket where you will put temporarily the content of one of them so that can be replaced with the content you want. See the example below
<?php
// variable declaration
$var_1 = "some content";
$var_2 = "some other content";
$temp_bucket = "";
//this is the swap
$temp_bucket = $var_1; // now $temp_bucket has $var_1 content
$var_1 = $var_2; // we move the $var_2 content into $var_1
$var_2 = $temp_bucket; // we move the $temp_bucket content into $var_1
echo "Job done!";
?>
Hope you enjoyed and if so, don’t forget to share!
Share this content: