views:

166

answers:

1

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 other idea.

Thanks

+2  A: 

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?

Yacoby
second array is numeric array whether first array is associative array whose key is idnetical to second array valuethats y i use `$ok` only
diEcho
It doesn't really matter - you can use `$key => $val` syntax on numerical arrays as well.
Amber
i used `array_flip` for the other array now both array's key are used in foreach
diEcho