Jump to content
J_Szwarga

Limiting Foreach Loops

Recommended Posts

All new to Processwire and PHP so be patient!

I'm trying to display multiple speakers for some events using a foreach loop. Not all the events have multiple speakers though.

So, how can I limit the foreach loop so it stops running all the empty divs?

At the top of my php file is this code:

 

<?php namespace ProcessWire
foreach($page->speaker as $speaker):
$thumb = $speaker->photo->width(310);
endforeach;
?>

code.png

Screenshot 2018-07-13 11.26.39.png

Share this post


Link to post
Share on other sites

You could check if speaker exists, but why do you have empty speakers in backend? In this case you can check for title or thumb or any requierd field

<?php 
foreach($page->speaker as $speaker) {
  if(!empty($speaker->photo) {
      // speaker markup
  }
}

:

 

 

Share this post


Link to post
Share on other sites

@J_Szwarga

It's not clear what do you want to limit? If you use the page reference field for assigning speakers, so you actually limit the list of speakers for certain event by this field. 

Share this post


Link to post
Share on other sites
1 minute ago, Zeka said:

@J_Szwarga

It's not clear what do you want to limit? If you use the page reference field for assigning speakers, so you actually limit the list of speakers for certain event by this field. 

Do you notice in my screenshot of my site, there's extra divs being generated? I think it's a problem with my foreach loop. I'm guessing the solution would be to stop the foreach loop after all the page references are echoed...if that makes any more sense.

Share this post


Link to post
Share on other sites

To be honest, I dont really see the empty divs in your sreenshot. However, a foreach loop should only output the exact number of items selected, unless you have a open tag/closing tag out of place.

Share this post


Link to post
Share on other sites

The second foreach($speaker as $thumb) looks like there is something missing.

I'd expect something like this there:

<?php foreach($speaker->photo as $thumb) {
 //
}

And I would remove the very first part of code.

<?php 
foreach($page->speaker as $speaker):
$thumb = $speaker->photo->width(310);
endforeach;

 

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...