Jump to content

[SOLVED] how to print a variable variable $GLOBALS array


dsaba

Recommended Posts

here is an array:

$sampleArray_1[] = 'hello';
$sampleArray_1[] = 'world';

 

a function:

$number = 1;
function whatever($num) {
$array = 'sampleArray_'.$num;
print_r($GLOBALS[$$array]);
}
whatever($number);

 

it does not print the $sampleArray

How do I do this correctly? as you can see I am using a dynamic variable name with the variable variable syntax

 

if I do this outside the function:

$num = 1
$array = 'sampleArray'.$num;
print_r($$array);

 

it prints out just fine

 

 

also, if I do this inside the function:

print_r(GLOBALS['sampleArray_1']);

it also prints out fine

 

 

it is doing this variable variable syntax accessing within the function that is causing problems

how do I do it correctly?

 

-thank you

You're not really using variable variables here, just use the index plain:

<?php
$sampleArray_1[] = 'hello';
$sampleArray_1[] = 'world';

function whatever($num) {
$array = 'sampleArray_'.$num;
echo '<pre>' . print_r($GLOBALS[$array],true) . '</pre>';
}

whatever(1);
?>

 

Ken

your solution works! thanks

 

 

however you said that I don't need to use variable variables, or that I am not using variable variables??

 

because if you are saying that I am not using variable variables then what do you call this?

$num = 1

$array = 'sampleArray'.$num;

print_r($$array);

 

 

I call that using variable variable syntax, so is that what its called or what?

(ugh... this terminology)

no, ken said that you don't need to use variables variables you just use $array as a normal index to the $GLOBALS superglobal.

 

You only need to use $array as a variable variable if you wasn't using the $GLOBALS superglobal.

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.