zzzplayer
zzzplayer

Reputation: 15

PHP Variable Variables and Array Index

I think this can be a simple problem for some of you. I've discovered similar questions, but they don't exactly solve my problem.

I've two arrays.

$array_numerals

Array
(
[2] => two
[3] => three
[4] => four
[5] => five
[6] => six
[7] => seven
)

$array_two

Array
(
[0] => $100
[1] => $200
[2] => $300
)

If I use

echo $array_two[0];

it shows the output properly, which is $100, as expected.

what I want to do is to make the "two" and the "[0]" dynamic. the "two" can be replced with "three" or "four" while the "[0]" can be replaced with "[1]" or "[2]".

So if I use

$i = 2;
$j = 0;

echo $array_{$array_numerals[$i]}[$j];

it doesn't work and shows empty value.

Edit: Thank you all for the comments and answers. I must add that $array_two, $array_three, etc. are fixed variables given by another source, so it's not like I can control the initial construction of these arrays. Hence, the answers given by some of you won't work out of the box (not your fault of course, perhaps I didn't clarify enough in the beginning). The answers given by Amadan and LuvnJesus work the best.

Upvotes: 1

Views: 1273

Answers (5)

Ali
Ali

Reputation: 1438

You can use PHP's compact function. I have used your array and created result as you need. please check here

Upvotes: 0

LuvnJesus
LuvnJesus

Reputation: 631

First, create the "name" of the array and store it in a variable:

$arrayname = "array_".$array_numerals[$i];

Store the array values into a new array

$newarray = $$arrayname;

Now output whichever elements you wish:

echo $newarray[$j];

Altogether you have:

$arrayname = "array_".$array_numerals[$i];
$newarray = $$arrayname;
echo $newarray[$j];

Upvotes: 0

Amadan
Amadan

Reputation: 198388

echo ${"array_$array_numerals[$i]"}[$j];

But I must warn you that it is a very bad idea to do this. Rather, use another lookup array:

$array = Array(
  0 => Array(
    2 => "$100",
    ...
  ),
  ...
);

echo $array[$i][$j];

Upvotes: 4

JoCoaker
JoCoaker

Reputation: 643

Can you just use it like this:

$array_two[0] = $array_two[1];

And do the same thing with the other array.

Upvotes: 0

Sanxofon
Sanxofon

Reputation: 981

Why not just use:

$array['two'][0]
$array['three'][0]
$array['four'][0]
$array['four'][1]
etc...

Upvotes: 0

Related Questions