views:

132

answers:

3

Hello,

I am creating a series of arrays from template tags in a content management system, and outputting the titles of these arrays as arrays labeled with variables:

<Loop>

$<GeneratedArrayName1> = array( "foo" => "bar" );

$<GeneratedArrayName2> = array( "foo" => "bar" );

</Loop>

I'm also generating another array of possible GeneratedArrayNames and sorting it by count. I'm looping through this array to get the GeneratedArrayNames so I can selectively show them. After I sort, I want to pull and display only a few of the many arrays I have with GeneratedArrayNames. I'm doing this by positioning the pointer at the top of the master array and getting the name:

reset($ArrayNames);
$firstArray = current($ArrayNames); //outputs GeneratedArrayName1

Then I went to pull the GeneratedArrayName by getting the Variable variable, which gives me an error:

print_r(${$firstArray}); // outputs Undefined variable: GeneratedArrayName1

But when I hardcode, I get the correct data:

print_r($GeneratedArrayName1); // outputs the array

Where am I going wrong?

EDIT

I am getting $firstArray by this loop:

$count = 0;
foreach($ArrayNames as $ArrayCount => $ArrayName) {

$count++;
echo "$ArrayName" . ' - ' . "$ArrayCount" . '<br>';

if ($count >= 3) {
 break;
 }

} //from here I proceed to reset($ArrayNames)
+1  A: 

try $$firstArray instead of ${$firstArray}

Chacha102
I get the same error
al
A: 

This code works fine:

$foo=array(3,2,1);
$foostr="foo";
print_r(${$foostr});

Which is exactly what you're doing. There must be an error in your code. Somehow, $GeneratedArrayName1 is not getting generated by the point your statement attempts to print it at.

Try checking the input variable - make sure there are no spaces on the beginning or end of it. trim() it if you must.

If none of that works, please edit your post the smallest amount of code (in full) that produces this error and we'll take a look at it.

ryeguy
It worked when I changed $firstArray to a string, but $firstArray is a value in an array that I am pulling with current(). Is there a way I can get PHP to treat it as a normal string?
al
print_r `$firstArray` just to double check.
Chacha102
`print_r($firstArray)` outputs `GeneratedArrayName1`, not the array contents.
al
The value returned by current() should be a string. There really is no reason PHP would interpret it as anything else. Oh, also, the call to current() isn't needed..reset() will return the first element, so calling current() is redundant.
ryeguy
Try $firstArray=(string)reset($ArrayNames);
ryeguy
Come to think of it, why can't you just do $ArrayNames[0]? It would get the first element.
ryeguy
that worked, ryeguy, thanks!
al
A: 

Is there a reason you're not using multidimensional arrays? That syntax is a lot clearer imho than variable variables.

Niels Bom