开发者

how to run foreach loop with ternary condition

i have two foreach loop to display some data, but i want to use a single foreach on basis of database result.

means if there is any row returns from database then forach($first as $fk=>$fv) should execute otherwise foreach($other as $ok) should execute. i m unsing below ternary operator which gives parse error

$n=$db->numRows($taskData); // databsse results

<?php ($n) ? foreach ($first as $fk=>$fv) : foreach ($other as $ok) 
{ ?>
<table><tr><td>......some data...</td></tr></table>
<?php } ?>

please suggest me how to handle such condition via ternary operator or any oth开发者_开发百科er idea.

Thanks


Use the conditional operator to select the array to use and then use $fv as the value rather than $ok for the second option.

foreach ( ($n ? $first : $other) as $fk => $fv )

Having two totally different loops being selected by a condition and with totally different variables would not really be a good idea as it would lead to really confusing code as you wouldn't be sure without checking $n which of $fk, $fv and $ok were set.

If you do need to do something different depending on the condition maybe the sections of code that are the same into functions would be a better idea?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜