spertuit Posted June 29, 2013 Share Posted June 29, 2013 I have a simple function public function showtrips($id,$table){ $sql="SELECT * FROM $table WHERE id = :id ORDER BY id DESC"; if(!$stmt = $this->conn->prepare($sql)){ // prepare failed echo "<pre>Prepare failed:\n"; print_r($pdo->errorInfo()); echo "</pre>"; } else { if(!$stmt->execute(array(':id'=>$id))){ // execute failed echo "<pre>Execute failed:\n"; print_r($stmt->errorInfo()); echo "</pre>"; } else { while($r = $stmt->fetch(PDO::FETCH_ASSOC)){ $data[]=$r; } return $data; } } } and a for loop that calls this function foreach($obj->showtrips($id,"trips") as $value){ extract($value); echo <<<show <tr class="success"> <td>$departTime</td> <td>$departPlace</td> <td>$arriveTime</td> <td>$arrivePlace</td> <td>$numberOfPass</td> <td>$purpose</td> <td>$cargo</td> <td>$remarks</td> </tr> show; } In my foreach loop how can I first test if the return variable $data has any data in it? Quote Link to comment Share on other sites More sharing options...
Solution mac_gyver Posted June 29, 2013 Solution Share Posted June 29, 2013 other than returning an empty array that would cause the foreach(){} loop to be skipped, you cannot specifically test for any condition in the foreach() statement. you would need to assign the result from the function to a variable, then test that variable before the foreach(){} statement. the only way you could alter the execution path based on there being no data would be to have the foreach(){} loop inside a try/catch block and throw an exception inside the function. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.