Werid Output from a foreach statement

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
User avatar
tecktalkcm0391
DevNet Resident
Posts: 1030
Joined: Fri May 26, 2006 9:25 am
Location: Florida

Werid Output from a foreach statement

Post 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!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
tecktalkcm0391
DevNet Resident
Posts: 1030
Joined: Fri May 26, 2006 9:25 am
Location: Florida

Post by tecktalkcm0391 »

I forgot to put what $other is.... sorry. :oops: its is:

[Color] Green ~ [Year] 2006 ~ [Intel] 3
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
tecktalkcm0391
DevNet Resident
Posts: 1030
Joined: Fri May 26, 2006 9:25 am
Location: Florida

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