Kevin Kevin - 5 months ago 19
PHP Question

foreach prints both results

<?php
foreach ($myassignment->result() as $e){
$courseId=$e->courseId;
$getassign=$this->Usermodel->getmysubassignment($courseId);

if($getassign->num_rows()==''){
print_r('no rows');
} else {
print_r('some rows');
}
}
?>


In the above code $myassignment contains 2 courseId's. In that first courseId doesn't return anything from DB using
$getassign=$this->Usermodel->getmysubassignment($courseId);
and second one return something. But it prints both
no rows
and
some rows
but I need only
some rows
. What to do?

Answer Source

You can't react to a future iteration of the loop. Just move your output outside the loop:

$resultscount = 0;
foreach ($myassignment->result() as $e)
 {
  ...
  $resultscount += $getassign->num_rows();
 }
if ($resultscount > 0) // good catch, Saty. Thanks!
 {
  print_r('some rows');
  // you can now also use the number of rows in output:
  print_r($resultscount . ' row' . ($resultscount > 1 ? 's' : ''));
 }
else
  print_r('no rows');