Jump to content

If else not working


Peter Knight
 Share

Recommended Posts

I'm trying a twist on a simple if / else statement.

  1. If the blog_category field is populated (page select), display the categories.
  2. If not, don't output anything.

This works:

<?php		
if ($page->blog_category){
    foreach($page->blog_category as $cat){
    echo"<a href=\"{$cat->url}\">{$cat->title}</a></li> ";} 

else {
    echo"";}
?>

But I've an added complication that the Categories need to have a "Posted under" before the very first Category.

I've tried variations on the code below and the first part works but even if there are no categories selected, I still get "posted under" appearing on the page.

<?php		
if ($page->blog_category){
  echo"Posted under: ";
  foreach($page->blog_category as $cat){
    echo"<a href=\"{$cat->url}\">{$cat->title}</a></li> ";} 
} 
else {
  foreach($page->blog_category as $cat){
    echo"";}
}							
?>

Have run my PHP through an online syntax checker and it's not showing any errors so it must be an issue.

Any tips?

Link to comment
Share on other sites

<?php		
// An object is always equal to true in php.
// For a PageArray do check for the number of elements.
// For a Page one would check for the id.

if ($page->blog_category->count()){

  echo"Posted under: ";
  foreach($page->blog_category as $cat){
    echo"<a href=\"{$cat->url}\">{$cat->title}</a></li> ";
  } 
} 
// Else do nothing. Not even loop though an empty array

@Mike Rockett

When using the new wire api function than do it the right way:

echo "Posted under: " . $page->blog_category->implode(", ", function($cat) {
    return "<a href=\"{$cat->url}\">{$cat->title}</a>";
});
  • Like 5
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...