Reference Variable in PHP

We have learned in the last tutorial, about Variable and its scope in PHP. Now, we will discuss some examples of variables and Data Types in PHP. But before that, if you have not seen the previous posts How to install PHP & Variable & its Scope in PHP, Please have a look at that first, and then continue with this post.

PHP $ and $$ Variables

What is $ variable or $$ variable?

  • The $var is a var variable created with single dollar is an ordinary variable, with the name var that stores any value like string, integer, float, etc.
  • The $$var double dollar is a reference variable that stores the value of the $variable inside it.

It allows you to have “Variables variable”, i.e., The string stored in normal variable allow users to create variable whose name is dynamic

To better understand consider this simple example:-

<?php

$blog=”Tekraze”;
$$blog=”Rahul CHANANA”;
echo $blog.” “;
echo $$blog.” “;
echo $Tekraze;

?>

OUTPUT:

Tekraze
Rahul CHANANA
Rahul CHANANA

In the above example,

  • $blog is just a variable with string value=“Tekraze”.
  • $$blog is reference variable . $$blog uses the value referenced by the variable $blog,
  • echo $blog print the value: Tekraze
  • echo $$blog print the value: Rahul CHANANA  value of this $blog variable is act as reference of second variable $$blog.
  • echo $Tekraze print the value : Rahul CHANANA,  Here $Tekraze also act as reference variable.

Let’s take an another example now using $ ,$$ and $$$

<?php

$name=“Haryana”;${$name}=“Chandigarh”;
${${$name}}=“Hisar”;
echo $name. “<br>”;
echo ${$name}. “<br>”;
echo $Haryana. “<br>”;
echo ${${$name}}. “<br>”;
echo $Chandigarh. “<br>”;

?>

OUTPUT:

Haryana
Chandigarh
Chandigarh
Hisar
Hisar

In the above example, we have assigned a value to the variable name Haryana. Value of reference variable ${$name} is assigned as Chandigarh and ${${$name}} as Hisar.

Now we have printed the values as $name, ${$name}, $Haryana, ${${$name}} and $Chandigarh.

So this is for today, in our next tutorial we will learn about Data Types in PHP. Stay connected with us for more tutorials.

If you like this tutorial please share it with your friends, colleagues and with your relatives, keep visiting and be a part of the Tekraze family. If you have any problem with this tutorial please comment in the comment box and if you have any suggestion regarding this then please tell us.