Jump to content

Archived

This topic is now archived and is closed to further replies.

shocker-z

function to alternate row colours not working

Recommended Posts

My code below is outputting 'bg2' all the time and not alternating..
can anyone see what i've done wrong?
bg1, bg2 are both classes stores in an attached CSS sheet
<?php
$row_count=1;

function altcolor($link) {
$bg1='bg1';
$bg2='bg2';
$class = ($row_count % 2) ? $bg1 : $bg2;
echo("class='$class' onmouseover=\"this.className='bgmouseover'\" onmouseout=\"this.className='$class'\" onclick=\"location.href='index.php?cat=profiles&page=viewprofile&username=$link'\"");
$row_count++;
}
?>


Regards
Liam

Share this post


Link to post
Share on other sites
It's not alternating because the variable $row_count is not known to the function so it's value is zero every time you enter the function.

In the function either add a "global" statement:
[code]<?php
$row_count=1;

function altcolor($link) {
   global $row_count;  // added
   $class = ($row_count % 2) ? 'bg1' : 'bg2';
   echo("class='$class' onmouseover=\"this.className='bgmouseover'\" onmouseout=\"this.className='$class'\" onclick=\"location.href='index.php?cat=profiles&page=viewprofile&username=$link'\"");
   $row_count++;
}
?>[/code]
Or make the function accept the value of $row_count as a parameter and return the next value of row_count:
[code]<?php
$row_count=1;
//
//
$row_count = altcolor($link,$row_count);   //<-- sample call of the function
//
function altcolor($link,$rc) {
$class = ($rc % 2) ? 'bg1' : 'bg2';
echo("class='$class' onmouseover=\"this.className='bgmouseover'\" onmouseout=\"this.className='$class'\" onclick=\"location.href='index.php?cat=profiles&page=viewprofile&username=$link'\"");
return($rc++);
}
?>[/code]

Many people seem prefer the second method over the first.

Ken

Share this post


Link to post
Share on other sites
thanks alot! thats great mate :) i never realised that it didnt take in variables from the outside or aless stated as global.. maby that has caused me un nessorcery headaches in the past :) i prefer the first option :)

Thanks alot
Liam

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.