Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Checking a DataObject isn't empty before attempting foreach loop


Reply


3 Posts   2526 Views

Avatar
Tama

Community Member, 132 Posts

15 July 2010 at 11:13am

I'm trying to work out how to check that a DataObject is populated before running it through a foreach loop. Here is what I came up with:

   function LatestNews($num=5) {
      
      $GetNews = DataObject::get("NewsPage", "ParentID = $this->ID", "DisplayDate DESC", "", $num);
      $LatestNews = new DataObjectSet();
      
      foreach(empty($GetNews)?array():$GetNews as $NewsItem){
         
         $LongDate = date("l j F Y",strtotime($NewsItem->DisplayDate));
         
         $extrainfo = array(
            'ArticleTitle' => $NewsItem->Title,
            'ArticleLink' => $NewsItem->Link(),
            'DisplayDate' => $LongDate,
            );
         $LatestNews -> push(new ArrayData($extrainfo));
      }
      
      return $LatestNews;
   }


As you can see I'm using

foreach(empty($GetNews)?array():$GetNews as $NewsItem)

so it gracefully fails if $GetNews is empty.

This works well in our development website but when I rolled it across to our production site it breaks with the following error when the DataObject is not empty - if the DataObject is empty I do not get an error:

[Notice] Trying to get property of non-object

Line 25 in /var/www/sites/wwwtasman/mysite/code/NewsListPage.php

25          $LongDate = date("l j F Y",strtotime($NewsItem->DisplayDate));

The only difference I can make up between the two websites is that our development website is running a slightly higher version of PHP (5.2.11) versus our production website (5.2.10).

All of this is pretty frustrating and I was wondering what tried and true method people use to make sure that if a DataObject is empty a foreach loop is not run.

Cheers
Tama

Avatar
3dgoo

Community Member, 133 Posts

15 July 2010 at 12:34pm

Wrap an if statement around the foreach:

if ($GetNews)
{
   foreach($GetNews as $NewsItem)
   {
      // do your stuff here
   }
}

Avatar
Tama

Community Member, 132 Posts

15 July 2010 at 12:37pm

Hi Ampedup

That was my original idea but I thought there must be a way that was "cleaner".

I think I've probably tried to be too clever and shot myself in the foot :p