1

Good day,

I'm currently trying to figure out how I can use a character stored inside a variable to call another variable by name. For instance:

$string = "ABCD";
$A = 10;
echo //Here I want to get $string[0]'s value, which will be A, then echo the value of the variable named after $string[0]'s value, $A. So in other words the output of the echo should be 10.

Let me know if I'm not clear enough on the question.

NodziGames
  • 395
  • 3
  • 17

3 Answers3

1

You should refer to PHP Variable variables.

A variable variable takes the value of a variable and treats that as the name of a variable.

Try one of these:

$string = "ABCD";

echo ${$string[0]};  // 10
echo $$string[0];    // 10
Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
  • Thank you so much! This is perfect. I tried using variable variables, but it didn't print out anything. I realized that it's because I defaulted all the variable to false. – NodziGames Sep 28 '16 at 06:39
1

Welcome to SO,

As per your asking about Let me know if I'm not clear enough on the question., I love this one cause you are new to this site. Now lets go to the field.

You have a variable: $string = "ABCD";, and also another is $A = 10;, or $B = 10; and so on.

What you really want to know is how to get the same value using the $string values??

Solution:
The logic behind this is called variables.variable, Let you are using the index of the string.

$string = "ABCD"; // your variable
$A = 10;          // your another variable
$B = 10;          // may your another variable

Now, Let $string[0], In this variable we have the a value and the value is A, So if we put a $ sign before this value then what will happen?? This will create a new variable and if you echo it you will get the value of this new created variable if the variable has a value.

Just do it: echo ${$string[0]}; // 10

Murad Hasan
  • 9,565
  • 2
  • 21
  • 42
0

You could do a $arr1 = str_split($str); to get an array of chars, and then based on that array do the echo like this echo "$$arr1[0]"

Denis Solakovic
  • 245
  • 3
  • 12