How to read variable in php


Variables are "containers" for storing information.


Creating (Declaring) PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable:

After the execution of the statements above, the variable $txt will hold the value Hello world!, the variable $x will hold the value 5, and the variable $y will hold the value 10.5.

Note: When you assign a text value to a variable, put quotes around the value.

Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.

Think of variables as containers for storing data.


PHP Variables

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

Rules for PHP variables:

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ($age and $AGE are two different variables)

Remember that PHP variable names are case-sensitive!



Output Variables

The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

The following example will produce the same output as the example above:

Example

$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>

Try it Yourself »

The following example will output the sum of two variables:

Note: You will learn more about the echo statement and how to output data to the screen in the next chapter.


PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives an option to specify the data type expected when declaring a function, and by enabling the strict requirement, it will throw a "Fatal Error" on a type mismatch.

You will learn more about strict and non-strict requirements, and data type declarations in the PHP Functions chapter.




Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:

produces the exact same output as:

i.e. they both produce: hello world.

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.

Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of multiple parts, or when the property name contains characters that are not otherwise valid (e.g. from json_decode() or SimpleXML).

Example #1 Variable property example

class foo {
    var 
$bar 'I am bar.';
    var 
$arr = array('I am A.''I am B.''I am C.');
    var 
$r   'I am r.';
}
$foo = new foo();
$bar 'bar';
$baz = array('foo''bar''baz''quux');
echo 
$foo->$bar "\n";
echo 
$foo->{$baz[1]} . "\n";$start 'b';
$end   'ar';
echo 
$foo->{$start $end} . "\n";$arr 'arr';
echo 
$foo->{$arr[1]} . "\n";?>

The above example will output:

I am bar.
I am bar.
I am bar.
I am r.

Warning

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.

userb at exampleb dot org

12 years ago

//You can even add more Dollar Signs$Bar = "a";
 
$Foo = "Bar";
 
$World = "Foo";
 
$Hello = "World";
 
$a = "Hello";$a; //Returns Hello
 
$$a; //Returns World
 
$$$a; //Returns Foo
 
$$$$a; //Returns Bar
 
$$$$$a; //Returns a$$$$$$a; //Returns Hello
 
$$$$$$$a; //Returns World

  //... and so on ...//

?>

Anonymous

17 years ago

It may be worth specifically noting, if variable names follow some kind of "template," they can be referenced like this:

// Given these variables ...
$nameTypes    = array("first", "last", "company");
$name_first   = "John";
$name_last    = "Doe";
$name_company = "PHP.net";// Then this loop is ...
foreach($nameTypes as $type)
  print ${
"name_$type"} . "\n";// ... equivalent to this print statement.
print "$name_first\n$name_last\n$name_company\n";
?>

This is apparent from the notes others have left, but is not explicitly stated.

Anonymous

20 years ago

The 'dollar dereferencing' (to coin a phrase) doesn't seem to be limited to two layers, even without curly braces.  Observe:

$one = "two";
$two = "three";
$three = "four";
$four = "five";
echo $$$
$one; //prints 'five'.
?>

This works for L-values as well.  So the below works the same way:

$one = "two";
$
$one = "three";
$$
$one = "four";
$$$
$one = "five";
echo $$$
$one; //still prints 'five'.
?>

NOTE: Tested on PHP 4.2.1, Apache 2.0.36, Red Hat 7.2

Sinured

15 years ago

One interesting thing I found out: You can concatenate variables and use spaces. Concatenating constants and function calls are also possible.

define('ONE', 1);
function
one() {
    return
1;
}
$one = 1;

${

"foo$one"} = 'foo';
echo
$foo1; // foo
${'foo' . ONE} = 'bar';
echo
$foo1; // bar
${'foo' . one()} = 'baz';
echo
$foo1; // baz
?>

This syntax doesn't work for functions:

$foo = 'info';
{
"php$foo"}(); // Parse error

// You'll have to do:

$func = "php$foo";
$func();
?>

Note: Don't leave out the quotes on strings inside the curly braces, PHP won't handle that graciously.

wuhanqinb at gmail dot com

4 years ago

For example #1,line:
echo $foo->$baz[1] . "\n";
It should be:
echo $foo->{$baz[1]} . "\n";
to run correctly.

Nathan Hammond

14 years ago

These are the scenarios that you may run into trying to reference superglobals dynamically. Whether or not it works appears to be dependent upon the current scope.

$_POST

['asdf'] = 'something';

function

test() {
   
// NULL -- not what initially expected
   
$string = '_POST';
   
var_dump(${$string});// Works as expected
   
var_dump(${'_POST'});// Works as expected
   
global ${$string};
   
var_dump(${$string});

}

// Works as expected
$string = '_POST';
var_dump(${$string});test();?>

antony dot booth at nodomain dot here

20 years ago

You may think of using variable variables to dynamically generate variables from an array, by doing something similar to: -

foreach ($array as $key => $value)
{
  $
$key= $value;
}
?>

This however would be reinventing the wheel when you can simply use:

extract( $array, EXTR_OVERWRITE);
?>

Note that this will overwrite the contents of variables that already exist.

Extract has useful functionality to prevent this, or you may group the variables by using prefixes too, so you could use: -

EXTR_PREFIX_ALL

$array =array("one" => "First Value",
"two" => "2nd Value",
"three" => "8"
               
);extract( $array, EXTR_PREFIX_ALL, "my_prefix_");?>

This would create variables: -
$my_prefix_one
$my_prefix_two
$my_prefix_three

containing: -
"First Value", "2nd Value" and "8" respectively

J. Dyer

20 years ago

Another use for this feature in PHP is dynamic parsing.. 

Due to the rather odd structure of an input string I am currently parsing, I must have a reference for each particular object instantiation in the order which they were created.  In addition, because of the syntax of the input string, elements of the previous object creation are required for the current one.

Normally, you won't need something this convolute.  In this example, I needed to load an array with dynamically named objects - (yes, this has some basic Object Oriented programming, please bare with me..)

   include("obj.class"); // this is only a skeletal example, of course.
  
$object_array = array(); // assume the $input array has tokens for parsing.
  
foreach ($input_array as $key=>$value){
     
// test to ensure the $value is what we need.
        
$obj = "obj".$key;
         $
$obj = new Obj($value, $other_var);
        
Array_Push($object_array, $$obj);
     
// etc..
  
} ?>

Now, we can use basic array manipulation to get these objects out in the particular order we need, and the objects no longer are dependant on the previous ones.

I haven't fully tested the implimentation of the objects.  The  scope of a variable-variable's object attributes (get all that?) is a little tough to crack.  Regardless, this is another example of the manner in which the var-vars can be used with precision where tedious, extra hard-coding is the only alternative.

Then, we can easily pull everything back out again using a basic array function: foreach.

//...
  
foreach($array as $key=>$object){

      echo

$key." -- ".$object->print_fcn()."
\n"
;

   }

// end foreach   ?>

Through this, we can pull a dynamically named object out of the array it was stored in without actually knowing its name.

mason

12 years ago

PHP actually supports invoking a new instance of a class using a variable class name since at least version 5.2

class Foo {
   public function
hello() {
      echo
'Hello world!';
   }
}
$my_foo = 'Foo';
$a = new $my_foo();
$a->hello(); //prints 'Hello world!'
?>

Additionally, you can access static methods and properties using variable class names, but only since PHP 5.3

class Foo {
   public static function
hello() {
      echo
'Hello world!';
   }
}
$my_foo = 'Foo';
$my_foo::hello(); //prints 'Hello world!'
?>

herebepost (ta at ta) [iwonderr] gmail dot com

6 years ago

While not relevant in everyday PHP programming, it seems to be possible to insert whitespace and comments between the dollar signs of a variable variable.  All three comment styles work. This information becomes relevant when writing a parser, tokenizer or something else that operates on PHP syntax.

    $foo

= 'bar';
    $
/*
        I am complete legal and will compile without notices or error as a variable variable.
    */
       
$foo = 'magic';

    echo

$bar; // Outputs magic.?>

Behaviour tested with PHP Version 5.6.19

jefrey.sobreira [at] gmail [dot] com

7 years ago

If you want to use a variable value in part of the name of a variable variable (not the whole name itself), you can do like the following:

$price_for_monday = 10;
$price_for_tuesday = 20;
$price_for_wednesday = 30;$today = 'tuesday';$price_for_today = ${ 'price_for_' . $today};
echo
$price_for_today; // will return 20
?>

php at ianco dot co dot uk

13 years ago

// $variable-name = 'parse error';
// You can't do that but you can do this:
$a = 'variable-name';
$
$a = 'hello';
echo
$variable-name . ' ' . $$a; // Gives     0 hello
?>

For a particular reason I had been using some variable names with hyphens for ages. There was no problem because they were only referenced via a variable variable. I only saw a parse error much later, when I tried to reference one directly. It took a while to realise that illegal hyphens were the cause because the parse error only occurs on assignment.

marcin dot dzdza at gmail dot com

3 years ago

The feature of variable variable names is welcome, but it should be avoided when possible. Modern IDE software fails to interpret such variables correctly, regular find/replace also fails. It's a kind of magic :) This may really make it hard to refactor code. Imagine you want to rename variable $username to $userName and try to find all occurrences of $username in code by checking "$userName". You may easily omit:
$a = 'username';
echo $$a;

sir_hmba AT yahoo DOT com

19 years ago

This is somewhat redundant, but I didn't see an example that combined dynamic reference of *both* object and attribute names.

Here's the code:

class foo
{
    var
$bar;
    var
$baz;

    function

foo()
    {
       
$this->bar = 3;
       
$this->baz = 6;
    }
}
$f = new foo();
echo
"f->bar=$f->bar  f->baz=$f->baz\n"; $obj  = 'f';
$attr = 'bar';
$val  = $$obj->{$attr};

echo

"obj=$obj  attr=$attr  val=$val\n";
?>

And here's the output:

f->bar=3  f->baz=6
$obj=f  $attr=bar  $val=3

nils dot rocine at gmail dot com

10 years ago

Variable Class Instantiation with Namespace Gotcha:

Say you have a class you'd like to instantiate via a variable (with a string value of the Class name)

class Foo
{
    public function
__construct()
    {
        echo
"I'm a real class!" . PHP_EOL;
    }
}
$class = 'Foo';$instance = new $class;?>

The above works fine UNLESS you are in a (defined) namespace. Then you must provide the full namespaced identifier of the class as shown below. This is the case EVEN THOUGH the instancing happens in the same namespace. Instancing a class normally (not through a variable) does not require the namespace. This seems to establish the pattern that if you are using an namespace and you have a class name in a string, you must provide the namespace with the class for the PHP engine to correctly resolve (other cases: class_exists(), interface_exists(), etc.)

namespace MyNamespace;

class

Foo
{
    public function
__construct()
    {
        echo
"I'm a real class!" . PHP_EOL;
    }
}
$class = 'MyNamespace\Foo';$instance = new $class;?>

nullhility at gmail dot com

14 years ago

It's also valuable to note the following:

${date("M")} = "Worked";
echo ${
date("M")};
?>

This is perfectly legal, anything inside the braces is executed first, the return value then becomes the variable name. Echoing the same variable variable using the function that created it results in the same return and therefore the same variable name is used in the echo statement. Have fun ;).

chrisNOSPAM at kampmeier dot net

21 years ago

Note that normal variable variables will not be parsed in double-quoted strings. You'll have to use the braces to make it work, to resolve the ambiguity. For example:

$varname = "foo";
$foo = "bar";

print $

$varname// Prints "bar"
print "$$varname"// Prints "$foo"
print "${$varname}"; // Prints "bar"
?>

dlorre at yahoo dot com

12 years ago

Adding an element directly to an array using variables:

$tab = array("one", "two", "three") ;
$a = "tab" ;
$
$a[] ="four" ; // <==== fatal error
print_r($tab) ;
?>
will issue this error:

Fatal error: Cannot use [] for reading

This is not a bug, you need to use the {} syntax to remove the ambiguity.

$tab = array("one", "two", "three") ;
$a = "tab" ;
${
$a}[] =  "four" ; // <==== this is the correct way to do it
print_r($tab) ;
?>

coviex at gmail dot com

9 years ago

In 5.4 "Dynamic class references require the fully qualified class name (with the namespace in it) because at runtime there is no information about the current namespace." is still true.
Neither simple class name nor containing subnamespace works.
Initial source: https://bugs.php.net/bug.php?id=45197

Omar Juvera

11 years ago

The example given in the php manual is confusing!
I think this example it's easier to understand:

//Let's create a new variable: $new_variable_1
$var_name = "new_variable_1"; //$var_name will store the NAME of the new variable

//Let's assign a value to that [$new_variable_1] variable:

$$var_name  = "value 1"; //Value of $new_variable_1 = "value 1"echo "VARIABLE: " . $var_name;
echo
"
"
;
echo
"VALUE: " . $$var_name;
?>

The OUTPUT is:
VARIABLE: new_variable_1
VALUE: value 1

You can also create new variables in a loop:
for( $i = 1; $i < 6; $i++ )
{
$var_name[] = "new_variable_" . $i; //$var_name[] will hold the new variable NAME
}

${

$var_name[0]}  = "value 1"; //Value of $new_variable_1 = "value 1"
${$var_name[1]}  = "value 2"; //Value of $new_variable_2 = "value 2"
${$var_name[2]}  = "value 3"; //Value of $new_variable_3 = "value 3"
${$var_name[3]}  = "value 4"; //Value of $new_variable_4 = "value 4"
${$var_name[4]}  = "value 5"; //Value of $new_variable_5 = "value 5"echo "VARIABLE: " . $var_name[0] . "\n";
echo
"
"
;
echo
"VALUE: " . ${$var_name[0]};
?>

The OUTPUT is:
VARIABLE: new_variable_1
VALUE: value 1

sebastopolys at gmail dot com

19 days ago

In addition, it is possible to use associative array to secure name of variables available to be used within a function (or class / not tested).

This way the variable variable feature is useful to validate variables; define, output and manage only within the function that receives as parameter
an associative array :
    array('index'=>'value','index'=>'value');
index = reference to variable to be used within function
value = name of the variable to be used within function

$vars

= ['id'=>'user_id','email'=>'user_email'];validateVarsFunction($vars);

function

validateVarsFunction($vars){//$vars['id']=34; <- does not work
     // define allowed variables
    
$user_id=21;
    
$user_email='';

     echo

$vars['id']; // prints name of variable: user_id
    
echo ${$vars['id']}; // prints 21   
    
echo 'Email: '.${$vars['email']};  // print

     // we don't have the name of the variables before declaring them inside the function

}
?>

Anonymous

29 days ago

I've found this could be useful in some way for using on multidimensional arrays:

       $f="1";$g="2";$h="3";
        $m="4";$n="5";$b="6";
        $q="7";$w="8";$e="9";
        $s="10";$d="11";$a="12";
        $l="13";$o="14";$p="15";
        $x="16";$c="17";$v="18";

                $one=["f","g","h"];
        $two=["m","n","b"];
        $three=["q","w","e"];
        $four=["s","d","a"];
        $five=["l","o","p"];
        $six=["x","c","v"];

                        $first = array("one", "two", "three") ;
        $second = array("four", "five", "six") ;

        $a = ["first","second"] ;

                print_r(${${${$a[1]}[1]}[1]});    // 16

derek at deperu dot com

1 year ago

How to use variable variables with for and foreach():

$obj_1 = array("one" => "One", "two" => "Two", "three" => "Three");
$obj_2 = array("one" => "Four", "two" => "Five", "three" => "Six");
$obj_3 = array("one" => "Seven", "two" => "Eight", "three" => "Nine");

for (

$i=1; $i < 4; $i++) {

    foreach (${

"obj_".$i} as $key => $value) {

                echo

$key . ': ' . $value."\n";

    }
}

?>

Result:

one: One
two: Two
three: Three
one: Four
two: Five
three: Six
one: Seven
two: Eight
three: Nine

mstearne at entermix dot com

21 years ago

Variable variables techniques do not work when one of the "variables" is a constant.  The example below illustrates this.  This is probably the desired behavior for constants, but was confusing for me when I was trying to figure it out.  The alternative I used was to add the variables I needed to the $GLOBALS array instead of defining them as constants.

define

("DB_X_NAME","database1");
define("DB_Y_NAME","database2");
$DB_Z_NAME="database3";

function

connectTo($databaseName){
global
$DB_Z_NAME; $fullDatabaseName="DB_".$databaseName."_NAME";
return ${
$fullDatabaseName};

}

print

"DB_X_NAME is ".connectTo("X")."
"
;
print
"DB_Y_NAME is ".connectTo("Y")."
"
;
print
"DB_Z_NAME is ".connectTo("Z")."
"
; ?>
[Editor Note: For variable constants, use constant() --Philip]

the_tevildo at yahoo dot com

14 years ago

This is a handy function I put together to allow variable variables to be used with arrays.

To use the function, when you want to reference an array, send it in the form 'array:key' rather than 'array[key]'.

For example:

function indirect ($var, $value)     // Replaces $$var = $value
{
  
$var_data = $explode($var, ':');
   if (isset(
$var_data[1]))
   {
      ${
$var_data[0]}[$var_data[1]] = $value;
   }
   else
   {
      ${
$var_data[0]} = $value;
   }
}
$temp_array = array_fill(0, 4, 1);
$temp_var = 1;
$int_var_list = array('temp_array[2]', 'temp_var');

while (list(

$key, $var_name) = each($int_var_list))
{
  
//  Doesn't work - creates scalar variable called "$temp_array[2]"
  
$$var_name = 0;
}
var_dump($temp_array);
echo
'
'
;
var_dump($temp_var);
echo
'
'
;//  Does work!$int_var_list = array('temp_array:2', 'temp_var');

while (list(

$key, $var_name) = each($int_var_list))
{
  
indirect($var_name, 2);
}
var_dump($temp_array);
echo
'
'
;
var_dump($temp_var);
echo
'
'
;
?>

Aycan Yat

8 years ago

Sometimes you might wish to modify value of an existing variable by its name. This is easily accomplishable with a combination of using "passing by reference" and "variable variables".

$first_var = 1;
$second_var = 2;
$third_var = 3;

$which_one = array_rand('first', 'second', 'third');
//Let's consider the result is "second".

$modifier = $$which_one;  //Now $modifier has value 2.
$modifier++; //Now $modifier's value is 3.
echo $second_var; //Prints out 2

//Consider we wish to modify the value of $second_var
$modifier = &$$which_one;  //Simply passing by reference
$modifier++; //Now value of $second_var is 3 too.
echo $second_var; //Prints out 3

It's that simple!

correojulian33-php at yahoo dot es

14 years ago

This example may help to overcome the limitation on $this.

Populate automatically fields of an object form a $_GET variable.

class pp{
   var
$prop1=1,$prop2=2,$prop3=array(3,4,5);

   function

fun1(){
     
$vars=get_class_vars('pp');
      while(list(
$var,$value)=each($vars)){
              
$ref=& $this->$var;
              
$ref=$_GET[$var];

      }

// while
     
var_dump($this);
   }
}
$_GET['prop1']="uno";
$_GET['prop2']="dos";
$_GET['prop3']=array('tres','cuatro','cinco','seis');$p=new pp();
$p->fun1();
?>

output is ...

object(pp)#1 (3) {
  ["prop1"]=>
  &string(3) "uno"
  ["prop2"]=>
  &string(3) "dos"
  ["prop3"]=>
  &array(4) {
    [0]=>
    string(4) "tres"
    [1]=>
    string(6) "cuatro"
    [2]=>
    string(5) "cinco"
    [3]=>
    string(4) "seis"
  }
}

dnl at au dot ru

21 years ago

By the way...
Variable variables can be used as pointers to objects' properties:

class someclass {
  var
$a = "variable a";
  var
$b = "another variable: b";
  }
$c = new someclass;
$d = "b";
echo
$c->{$d};
?>

outputs: another variable: b

jupp-mueller at t-online dot de

20 years ago

I found another undocumented/cool feature: variable member variables in classes. It's pretty easy:

class foo {
  function
bar() {
   
$bar1 = "var1";
   
$bar2 = "var2";
   
$this->{$bar1}= "this ";
   
$this->{$bar2} = "works";
  }
}
$test = new foo;
$test->bar();
echo
$test->var1 . $test->var2;
?>

houssemzitoun91 at gmail dot com

4 years ago

Even outside a function or a class method  variable variables cannot be used with PHP's Superglobal arrays. See the example bellow:

$a

= '$GLOBALS["a"]';

function

foo()
{
        global
$a;
        echo $
$a;
}

echo

$GLOBALS["a"], PHP_EOL; // $GLOBALS["a"]echo ${$a}; // PHP Notice:  Undefined variable: $GLOBALS["a"]

mccoyj at mail dot utexas dot edu

21 years ago

There is no need for the braces for variable object names...they are only needed by an ambiguity arises concerning which part of the reference is variable...usually with arrays.

class Schlemiel {
var
$aVar = "foo";
}
$schlemiel = new Schlemiel;
$a = "schlemiel";
echo $
$a->aVar;
?>

This code outputs "foo" using PHP 4.0.3.

Hope this helps...
- Jordan

Alex

2 years ago

If you want to use Variable Variables with $_POST,
you may follow this example:

// you created a form with variable names:
$_POST['content_1'] = "blabla";
$_POST['content_2'] = "blublu";
// ...
$_POST['content_99'] = "bleble"; // Then, you can use a loop:for ($i=1; $i<99;$i++)
{
echo
$_POST["content_$i"];
}
?>

How do you call a variable in PHP?

Rules for PHP variables:.
A variable starts with the $ sign, followed by the name of the variable..
A variable name must start with a letter or the underscore character..
A variable name cannot start with a number..
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).

How can access variable function in PHP?

Accessing global variable inside function: The ways to access the global variable inside functions are: Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.

What is $$ in PHP?

PHP | $ vs $$ operator The $ operator in PHP is used to declare a variable. In PHP, a variable starts with the $ sign followed by the name of the variable. For example, below is a string variable: $var_name = "Hello World!"; The $var_name is a normal variable used to store a value.

What are variable in PHP explain in detail?

Variable is a symbol or name that stands for a value. Variables are used for storing values such as numeric values, characters, character strings, or memory addresses so that they can be used in any part of the program. Declaring PHP variables.