Page 1 of 1

can i use two if statementes in foreach loop?

Posted: Tue Mar 02, 2010 5:28 am
by alega
Hi,

i'm interested: how to use two if statements in foreach loop to get different class for table row based on even or odd it is.
but my code doesn't work.

would be very grateful for pointing the mistake.



foreach ($row as $key=>$value){

$x =0;
$id = $value['id'];
$value = unserialize($value['user_data']);

if ($x%2 == 0)
{
print '<tr class="odd">';
}
elseif {
print '<tr>';
}
endif;

if (@array_key_exists('c19_2', $value)) {

echo'<td width="50" style="background:green;">';
print $id;
echo"<td />";

echo'<td width="50" style="background:red;">';

print $value['c19_2'];

echo"<td />";
$x++;
}

echo '</tr>'
}

Re: can i use two if statementes in foreach loop?

Posted: Tue Mar 02, 2010 6:24 am
by davex
Hi,

Yes you can - I think there are more than a few problems with your code though. At the very least you are setting $x to 0 in every loop so it will never be higher.

Here's an example I think of what you want:

Code: Select all

<?php
$my_array = new array("one","two","three","four","five","six","seven","eight","nine","ten");
 
$counter=1;
foreach($my_array as $array_item)
 {
 if ( ($counter%2)==0 )
  {
  echo "Even! ";
  }
 else
  {
  echo "Odd! ";
  }
 echo $array_item;
 echo "<BR />";
 $counter++;
 }
?>
Hope that helps.

Cheers,

Dave.