can i use two if statementes in foreach loop?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
alega
Forum Newbie
Posts: 3
Joined: Thu Feb 25, 2010 9:14 am

can i use two if statementes in foreach loop?

Post 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>'
}
davex
Forum Contributor
Posts: 101
Joined: Sat Feb 27, 2010 4:10 pm
Location: Namibia

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

Post 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.
Post Reply