2

How I can use variable variables with array to get result like is below?

I've tried so far:

// $g_module_id_bar_1['id'] = 5;

$i = 1;

$variablename = 'g_module_id_bar_'.$i;
$key = '\'id\'';

echo $$variablename[$key];

Result should be: 5

2
  • 3
    It's better to be $g_module_id_bars[1]['id'] = 5; Commented Jul 30, 2018 at 10:05
  • 1
    What version of PHP are you using? The changes made to Uniform Variable Syntax in PHP 7 will have an effect on how the last line is processed. Commented Jul 30, 2018 at 10:07

2 Answers 2

3

You almost had it.

Change $key = '\'id\''; too $key='id';

The reason is because PHP understands that $key contains a string. When accessing an array noramlly, you wouldn't do something like:

 <?php     
 $var = array("hello"=>"world");   
 echo $var["'hello'"];

which is effectively what you were doing

See for full solution: https://3v4l.org/qk5ZL

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, it was my mistake. Thanks for help.
@AdamMakowski =) np
1

You are trying to escape single quotes but this is useless, just use the string key:

$key = 'id';
echo $$variablename[$key]; // 5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.