Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.