简体   繁体   中英

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.

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];

Why not just use:

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

Can you just use it like this:

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

And do the same thing with the other array.

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];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM