Jump to content

Variable variable array


joe92

Recommended Posts

$word = 'numbers';
$numbers= array('1', '2', '3', '4');

echo $$word[0];

 

I expected the output to be '1'. It ended up being nothing...  :-\

 

Why does this not work? Is it not possible to have a variable variable array? And if not, is there a workaround?

 

Cheers,

Joe

Link to comment
Share on other sites

The square brackets can also return a given character in a string.

<?php 

$word = 'numbers';

echo $word[0];

?>

will output 'n'

 

What you want to do is use curly braces to let PHP know that you want the $word variable isolated from the $ at the start, and the [0] at the end.

<?php 

$word = 'numbers';
$numbers= array('1', '2', '3', '4');

echo ${$word}[0];

?>

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.