Variable variable OK! But with ARRAY indexes - problem!

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Post Reply
DoppyNL

Post by DoppyNL » Thu Oct 17, 2002 1:28 am

If you want to acces a variable with the name wich is stored in another variable, you will have to do this like this:

Code: Select all

$varname = 'variable_name';
$variable_name = 'Greetings Eartlings';
print($$varname);
this will output:
Greetings Earthlings
This is no different when using arrays or not.



When you want to use a variable to acces a specific index in you're array you can do that as follows:

Code: Select all

$my_array[12] = 'Greetings Eartlings';
$array_index = 12;
print($my_array[$array_index]);
this wil output:
Greetings Eartlings
This can be done with strings as well, works the same.


What you can't do is using 1 variable to acces a multi-dymension array:

Code: Select all

$my_array[12][15] = 'Greetings Eartlings';
$my_index = "[12][15]"
print($my_array[$my_index]); //-- or any variant
will not work!
You will have to use 2 variables to acces both indexes seperately.
Like this:

Code: Select all

$my_array[12][15] = 'Greetings Eartlings';
$my_index1 = 12;
$my_index2 = 15;
print($my_array[$my_index1][$my_index2];
will output:
Greetings Eartlings


Hope this helps.

Greetz Daan

DoppyNL

Post by DoppyNL » Thu Oct 17, 2002 2:02 am

As far as I know you can't acces a multi-level array like that (but I could be wrong).

a possible solution could be this:

Code: Select all

$your_array_name[1][3][12] = 'Greetings Earthlings';
$indexes = '[1][3][12]';
$tempvar = 'print($your_array_name' . $indexes . ');';
eval($tempvar);
$tempvar equals to this:
print($your_array_name[1][3][12]);
and the output is this:
Greetings Earthlings


It's not very nice coding, but it works.
I think there is a better way to do this, only I don't know it.
Perhaps someone else?

Greetz Daan

Jay

Post by Jay » Thu Oct 17, 2002 3:30 am

For the way you want to do it, the best solution is the eval() one!

Post Reply

Who is online

Users browsing this forum: No registered users and 3 guests