Loop past non object


I have a model that I want to loop thorugh all it’s Primary Keys, the problem I’m facing is that some Data has been deleted from that Model thus resulting in some empty objects. So PK 1,2,3 etc does not exist. So when I loop through them I get trying to get error “Propety of non-object”.

for ($i=0; $i<=100; $i++){

 $cat= Categories::model()->findByPk($i);

echo $cat->subcatCount;


If I put a specific number that I know exists in findByPk() it works fine. How can my loop keep going even if it encounters some non existing objects?



P.S this topic was in the 1.0.x forum, I realized my mistake so I deleted the old one (which had no replies anyway) and started it here.

I there a specific reason that you have to use a loop and query the database for each pk separately? Just asking, because you may want to use findAll() instead to only send a single query and not 100 separate ones. Or you could use findAllByPk providing an array of primary keys to do the same.

However, the problem above is a simple PHP issue. Just use an if statement and check if $cat is either null or an object:

for ($i=0; $i<=100; $i++){


    echo ($cat==null) ? null : $cat->subcatCount;


I wanted to print the amount of subcategories each Category has, I thought looping through all Categories will be the best solution (or the only solution I know). I’m still a novice user of PHP and yii tbh. So anything I try to implement is what I know of Java. The 100 will be changed to the length of categories.

Thanks so much for the reply, I figured I needed an If statement but my problem was that I placed my If before the loop so it was stopping the loop from starting.

Again Thank you, it works perfect.

Ok, so you want to get all categories? Use

$categories=Category::model()->findAll(); //returns an array of categories or an empty array if there aren't any

That is more performant, easier and it will always work, even if you add new categories