Kevin
Kevin

Reputation: 653

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?

Upvotes: 1

Views: 41

Answers (2)

Alien426
Alien426

Reputation: 1267

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');

Upvotes: 1

Saty
Saty

Reputation: 22532

Use a flag for that

$flag = FALSE;// set if false
    foreach ($myassignment->result() as $e) {
        $courseId = $e->courseId;
        $getassign = $this->Usermodel->getmysubassignment($courseId);

        if ($getassign->num_rows() > 0) {
            $flag = TRUE;// if row then set it true
        }
    }// end of foreach loop
    if ($flag) {
        print_r('some rows');
    } else {
        print_r('no rows');
    }

Upvotes: 1

Related Questions