Is it possible to use a variable variable as an array prefix? I have a set of arrays with the format $x_settings
, and I want to output the values of just one depending on which prefix matches a condition.
This is an extremely stripped-down version of much more complex code, so thanks for your indulgence:
$current_env = 'local';
$local_settings = array
(
'debug' => TRUE,
'cake' => TRUE,
'death' => FALSE
);
$environments = array
(
'local',
'dev',
'prod'
);
foreach( $environments as $env )
{
if( $current_env == $env )
{
define('DEBUG', ${$env}_settings['debug']);
define('CAKE', ${$env}_settings['cake']);
define('DEATH', ${$env}_settings['death']);
break;
}
}
As you can see I tried using ${$env}_settings[]
but that gave me a PHP error:
unexpected '_settings' (T_STRING)
Possible?
Yes, it is possible. Your loop should look like below:
foreach( $environments as $env )
{
if( $current_env == $env )
{
define('DEBUG', ${$env.'_settings'}['debug']);
define('CAKE', ${$env.'_settings'}['cake']);
define('DEATH', ${$env.'_settings'}['death']);
break;
}
}
Notes:
=
instead of =>
.break
inside your loop - otherwise, you'll be trying to re-declare constants and that will cause PHP to output errors=
to ==
. =
is the assignment operator. You need to use ==
(loose comparison) or ===
(strict comparison) instead.