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

No empty speakers. I'm using a page reference to assign certain speakers to certain camps

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

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

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...