Jump to content

Foreach call not working properly


Silster
 Share

Recommended Posts

Hi all,

Newbie here, so hopefully I'm not asking too silly a question.

Following a tutorial, I've set up a very simple site. I've created a page with three (test) childpages. The template file of the parent page is supposed to display all the child pages' fields using a foreach loop. The code I've inserted in the  template file is:

<div>
<?php 
foreach($page->children as $element); ?>
 
<h3><?=$element->sp_title; ?></h3>
<?=$element->sp_content; ?>
<? endforeach; ?>
</div>
 
It all seems to be working, but only the last child page's fields are returned in the output, and not all three pages as I was expecting (when I change the order of the child pages, the contents of the outputted field changes to the one that is the last child page now).
 
What am I doing wrong? The PHP is working, but the child pages do not seem to be traversed. Any help is welcome. Thanks in advance. 
 
/Silvio
Link to comment
Share on other sites

Please use the code tool of the editor here in the forums, this makes is easier to read. 

<div>
<?php foreach($page->children as $element) : ?> // <-- no semicolon, but a colon here
<h3><?=$element->sp_title; ?></h3>
<?=$element->sp_content; ?>
<?php endforeach; ?> // add the php
</div>

You're effektivly replacing {} with ":" … "end…;". The semicolon always marks the end of a statement, if it's a single line or a whole loop.

  • Like 1
Link to comment
Share on other sites

Hi LostKobraKai,
 
Thanks for the quick reply. I'm not very fluent in PHP, so I missed that one.
 
However, when I change the semicolon to a colon as you suggest, it throws up an error: Parse Error: syntax error, unexpected end of file (line 32...)
 
(Line 32 refers to the closing 

</html>

 tag in the template file.)

Link to comment
Share on other sites

For the sake of readability, I would format it somewhat differently. All those open/close tags make code hard to read :

<?php 
foreach($page->children as $element) { 
  echo "<h3>{$element->sp_title}</h3>";
  echo $element->sp_content;
} ?>

{} are used to explicitly tell PHP to evaluate a statement in a string, note this only works in double quotes. This isn't typically required, but it's good to get used to use it. Avoids some headaches, and you don't need to use "string" . $object->property . "string", which can save quite a bit of time in the long run. This is called complex/curly parsing, you can read more about it here: http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...