0

I'm trying to use a nested php array grabbed from a database in a loop to create a bunch of html elements.

Below is a cleaned up section of that code which still contains the strange error: non-nested arrays can be used properly, as in the code below:

   <?php
        $array = array();
        $array[] = "a";
        $array[] = "b";
        $array[] = "c";
        $x = 1;

        echo "<input type='radio' value=\" $array[$x] \" id='$x'> <label for=\" $array[$x] \">" . $array[$x] . "</label><br>";
    ?>

But not when the array is nested, as here:

    <?php
        $subarray = array();
        $subarray[] = "a";
        $subarray[] = "b";
        $subarray[] = "c";
        $array = array();
        $array[] = $subarray;
        $subarray[] = "p";
        $subarray[] = "q";
        $subarray[] = "r";
        $array[] = $subarray;
        $x = 1;
        echo "<input type='radio' value=\" $array[$x][$] \" id='$x'> <label for=\" $array[$x][1] \">" . $array[$x][1] . "</label><br>";
    ?>

For some strange reason, the "$array[$x][$x]" and "$array[$x][1]" only work outside of the "<>"-tags and brings about the "b" stored in the array at [1][1]. But within the "<>"-tags they only show as "Array[1]" in the inspector. The "$x" works fine within the "<>"-tags.

What can I do to make this work?

Thanks!

1 Answer 1

1

PHP's parser is not "greedy" for arrays:

$foo = array();
$foo[1] = array();
$foo[1][2] = 'bar';

echo "$foo";       // Output: Array
echo "$foo[1]"     // Output: Array
echo "$foo[1][2]"; // Output: Array[2]

For the 2nd and subsequent array "dimensions", you have to use the {} extended syntax:

echo "{$foo[1][2]}"; // Output: bar

Note that when using {} notation, string keys MUST be quoted:

echo "$foo[bar]"; // ok
echo "$foo['bar']"; // causes warning
echo "{$foo['bar']}"; // ok
echo "{$foo[bar]}"; // undefined constant warning
Sign up to request clarification or add additional context in comments.

2 Comments

Well, isn't that marvelous! Thanks! Why would it do that though?
because PHP's internal development consistency is about as appetizing as an unflushed bus stop toilet: none at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.