Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP nested foreach

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

like image 829
Jorge Avatar asked Dec 12 '25 00:12

Jorge


1 Answers

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

like image 106
Fabrizio D'Ammassa Avatar answered Dec 14 '25 14:12

Fabrizio D'Ammassa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!