0

We have a custom walker displaying only the sub menu of the current top menu and while making some changes to it I ran into something I don't get - for some reason only the first echo of each loop in the second foreach-loop will actually echo, while the following echos will only echo on the very last loop. Why is that?

This is the code:

    $top_level_elements = array();
    $children_elements  = array();
    foreach ( $elements as $e) {
        if ( 0 == $e->$parent_field )
            $top_level_elements[] = $e;
        else
            $children_elements[ $e->$parent_field ][] = $e;
    }

    foreach ( $top_level_elements as $e )
        echo 'One thing<br>'; // Note 1
        echo 'Another thing<br>'; // Note 2
        echo '$e->ID: ' . $e->ID . '<br>'; // Note 3
        if ( $e->current || $e->current_item_ancestor || $e->current_item_parent ) {
            $this->display_element( $e, $children_elements, $max_depth, 0, $args, $output );
        }

        return $output;
    }

Note 1-3 shows my test values. What is echoed is the following:

One thing
One thing
One thing
One thing
One thing
One thing
One thing
One thing
Another thing
$e->ID: 873

While if I remove Note 1-2 I'll get the following, i.e. all the IDs for the top menu items.

$e->ID: 7
$e->ID: 909
$e->ID: 42
$e->ID: 1326
$e->ID: 871
$e->ID: 872
$e->ID: 1383
$e->ID: 873

It's as if any statement within the loop makes every statement after it invalid, except for the on the last repeat. This isn't only true for echos, but for any operation it's just easier to display with echos.

This also means that if I echo test variables like the ones above, the menu won't show as by the time the script reaches the if-statement the variables $e->current etc. already seem empty.

And while I can get around this at this point, as I really don't need to echo stuff here, I really want to know why this is - as it means I can't do any operations within the loop before the if-statement or it will not run the if statement in most cases.

closed as off-topic by Michael, Rarst May 13 '14 at 11:30

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

3

Looks like you missed the { for foreach

Change this line:

foreach ( $top_level_elements as $e )

to

foreach ( $top_level_elements as $e ) {

And don't forget to complete the curly bracket after the end of loop.

  • Gaaah, don't I feel stupid now! In my defense I inherited the code and it was formatted in a way that you would assume there were curly brackets around the loop (and it worked), so I obviously didn't look at it close enough even though I could tell the error didn't make sense. Thank you so much for taking a look at it and seeing what I missed! – Linda H May 13 '14 at 11:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.