Page 1 of 1

Werid Output from a foreach statement

Posted: Wed Jan 03, 2007 6:11 pm
by tecktalkcm0391
I have this: Which is the $other in the code below:

Code: Select all

<table> <?php
function OddOrEven($intNumber){
	if ($intNumber % 2 == 0 ){
		//your number is even
		return "Even";
	} else {
		return "Odd";
	}
}

$rowcount = 0;
$new_tags = split('~', $other);
$trans = array();
foreach($new_tags as $tag){
	$split = split("]",$tag);
	$split[0] = str_replace('[','',$split[0]);
	$split[0] = trim($split[0]);
	$split[1] = trim($split[1]);
	$trans[] = array($split[0],$split[1]);
}
foreach($trans as $out){
	$rowcount = $rowcount + 1;
	$oddoreven = OddOrEven($rowcount);
	if($oddoreven=="Odd"){
		$output.='
		<tr>
			<td align="right">'.$out[0].':</td>
			<td colspan="3" style="padding-left:7px;">'.$out[1].'</td>
  		</tr> ';
	} else {
		$output.='
		<tr>
			<td align="right" bgcolor="#e9e9e9">'.$out[0].':</td>
			<td colspan="3" bgcolor="#e9e9e9"  style="padding-left:7px;">'.$out[1].'</td>
  		</tr>';
	}
	print($output);
}


?>
</table>
And I keep getting:

Code: Select all

Color: Green 
Color: Green 
Year: 2006 
Color: Green 
Year: 2006 
Intel: 3
When I should be getting:

Code: Select all

Color: Green 
Year: 2006 
Intel: 3
I just cant figure out why. Can some one please help!

Posted: Wed Jan 03, 2007 6:14 pm
by feyd
What's in $other?

It should be noted that split() uses regular expressions, which you aren't exploiting. Therefore explode() will run faster.

Posted: Wed Jan 03, 2007 6:16 pm
by tecktalkcm0391
I forgot to put what $other is.... sorry. :oops: its is:

[Color] Green ~ [Year] 2006 ~ [Intel] 3

Posted: Wed Jan 03, 2007 6:22 pm
by feyd
$output is never initialized and never cleared either. That is the source of your error. Basically, don't use concatenation if you're printing on each iteration.

Posted: Wed Jan 03, 2007 6:26 pm
by tecktalkcm0391
yeah i just relized what i did wrong and was about to post what was wrong... i meant to put the print($ouput); after the foreach..{...}