3

I thought that I understood php arrays, but it seems I don't :( This is my code:

<?php

// Create a magazines array
$magazines = array();

// Put 5 magazines on it
for($x=0;$x<5;$x++)
    $magazines[] = "Magazine " . $x ;


// Associate articles array to each magazine
foreach($magazines as $magazine){
    $articles[$magazine] = array();
    for($x=0;$x<3;$x++)
        $articles[$magazine] = $magazine . " - Article " . $x ;
}

// List them all
foreach($magazines as $magazine){
    echo $magazine . " has these articles: <br>";
    foreach($articles[$magazine] as $article)
        echo $article . "</br>";
}

?>

It only prints the magazines, not the articles inside each magazine. It's clear there is something I don't get about nested foreach loops. Could you please help me? What am I doing wrong? Thanks in advance! :)

Jorge
  • 259
  • 1
  • 7
  • 15

2 Answers2

4

You missed the [] in the nested loop:

<?php

// Create a magazines array
$magazines = array();

// Put 5 magazines on it
for($x=0;$x<5;$x++)
    $magazines[] = "Magazine " . $x ;


// Associate articles array to each magazine
foreach($magazines as $magazine){
    $articles[$magazine] = array();
    for($x=0;$x<3;$x++)
        $articles[$magazine][] = $magazine . " - Article " . $x ;
}

// List them all
foreach($magazines as $magazine){
    echo $magazine . " has these articles: <br>";
    foreach($articles[$magazine] as $article)
        echo $article . "</br>";
}

?>

This snippet should work

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Fabrizio D'Ammassa
  • 4,729
  • 25
  • 32
  • Hi Fabrizio, It works! Now I understand how it works and what my mistake was. Thank you so much! – Jorge Jul 23 '11 at 06:44
  • 1
    I came to the same conclusion (+1). It's also worth mentioning that this error could've been easily detected by setting `error_reporting` to `E_ALL | E_STRICT`. – vstm Jul 23 '11 at 06:44
2

Try changing this code part:

$articles[$magazine][] = $magazine . " - Article " . $x ;
czerasz
  • 13,682
  • 9
  • 53
  • 63