0

I want to define in PHP a new 2D array (to fill and access it later in cycle) but I have problem to deal with it. I went through some articles (e.g. here), but it still does not work for me.

My code is:

$part = array(array());
for ($i=0; $i<4; $i++) {
    for ($j=0; $j<3; $j++) {
        $part[$i][$j]=3;
    }
}

for ($i=0;  $i<4; $i++) {
    for ($j=0; $j<3; $j++) {
        echo "values i=$i, j=$j: $part[$i][$j]\n<br>";
    }
} 

Result of code above is:

Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 43
values i=0, j=0: Array[0]

Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 43
values i=0, j=1: Array[1]

Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 43
values i=0, j=2: Array[2]

Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 43
values i=1, j=0: Array[0]
...

Line 43 mentioned in output is:

echo "values i=$i, j=$j: $part[$i][$j]\n<br>";

I have tried to use also just a little bit modified version of code from above mentioned article, however result was same:

Code:

$a = array(); // array of columns
for($c=0; $c<5; $c++){
    $a[$c] = array(); // array of cells for column $c
    for($r=0; $r<3; $r++){
        $a[$c][$r] = rand();
        echo "$a[$c][$r] \n<br>";
    }
}

Result:

Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 55
Array[0]

Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 55
Array[1]

Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 55
Array[2]

Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 55
Array[0]
...

Line 55 mentioned above is:

echo "$a[$c][$r] \n<br>";

Could someone help me with this problem? Thanks.

Miil
  • 1

1 Answers1

2

You need to use braces in you use a "complex" expression in the string interpolation, i.e.

    echo "values i=$i, j=$j: {$part[$i][$j]}\n<br>";

Note the { ... } around the $part[$i][$j] part.

An expression becomes "complex" as soon as it's more than a plain variable name.

See PHP manual on simple string interpolation syntax and complex syntax.

Note that the complex syntax can be used for plain variables as well, i.e. you could use {$i} ... {$j} for consistency.

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103