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?

6
  • 1
    echo ${"my_array" . $x}[0]; Commented Apr 22, 2019 at 21:40
  • If I understand correctly, you want variable variables php.net/manual/en/language.variables.variable.php Commented Apr 22, 2019 at 21:40
  • @rjdown That's the title of the duplicate question I linked to. Commented Apr 22, 2019 at 21:42
  • Your question title is misleading. You don't want to use the variable in the index, you want to use it in the name of the variable. Commented Apr 22, 2019 at 21:43
  • 1
    But it's generally a bad idea to code like this. Use a 2-dimensional array instead. Commented Apr 22, 2019 at 21:50

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

You can do it, it's just not considered good style, and your method is preferable.
yes, thanks I update my comment
Thank you rapaelec. Your solution works also for me.
-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.

2 Comments

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.
My apologies, you're right ! Maybe I need an extra cup of coffee today...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.