What is the role of two $$ variables?

Just found this variable and wondering why this two $$ variables sign is required.

This is the simple code got from php doc

$var_name = 'var';
$var = [0,1,2,3,4];
echo $var_name[2];

Output → r (Why, I am getting “r” string, is this because the key is assigned to value “r”?)

$var_name = 'var';
$var = [0,1,2,3,4];
echo $$var_name[2];

Output - 2 [In php 7] , how this $$ works?

It calls variable variable.For example:

$a="name";
$b="a";
echo $$b;

//The echo outputs name

The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.

So, when to use in real world example?

never. really.

2 Likes

Thank you lol :smiley:

Because thats how it works. You can access characters in a string in array like way with indexes. But the string is not really an array even tho you can do that. You can’t for example use array functions with the string.

$var_name = 'var';
echo $var_name[0];  // Prints "v"
echo $var_name[1];  // Prints "a"
echo $var_name[2];  // Prints "r"
echo $var_name[3];  // Notice: Uninitialized string offset: 3
1 Like

Thanks, yeah I understood before your reply but again thanks for the explanation.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.