0

I have two arrays:

$my_array1= array("A", "B");
$my_array2= array("1", "2");

Is it possible to use variables ($x) in the index of the array like this:

for ($x = 1; $x <= 2; $x++) {
Echo $my_array.$x[0];
}

How to achieve this?

Sara Z
  • 625
  • 7
  • 18

2 Answers2

1

After referred in comment , i think it's work : here

$my_array1= array("A", "B");
$my_array2= array("1", "2");

and re-use your loop like:

    for ($x = 1; $x <= 2; $x++) {
    // to init the new name of array
    $init = 'my_array'.$x;
    // to use variable in the name of variable 
    Echo $$init[0];
    }

I hope it's help you

rapaelec
  • 1,238
  • 12
  • 10
-1

I think what you're looking for is to be able to use key / value pairs.

You can do something like:

$array = array(
    1    => "a",
    2  => "b",
    3  => "c",
    4 => "d",
);

foreach ($array as $key => $value) {
   echo "{$key} => {$value} ";
}

Or loop througout the numeric key values as you like.

francovici
  • 536
  • 6
  • 14
  • This doesn't seem related to the question at all. He wants to choose between `$my_array1` and `$my_array2` depending on the value of `$x`. – Barmar Apr 22 '19 at 21:40
  • My apologies, you're right ! Maybe I need an extra cup of coffee today... – francovici Apr 22 '19 at 21:49