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! :)

2
  • where those articles come from? Commented Jul 23, 2011 at 6:38
  • Did you mean to put the articles inside a magazine? 'cos your code's the other way around! Commented Jul 23, 2011 at 6:44

2 Answers 2

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

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

2 Comments

Hi Fabrizio, It works! Now I understand how it works and what my mistake was. Thank you so much!
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.
2

Try changing this code part:

$articles[$magazine][] = $magazine . " - Article " . $x ;

Comments

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.