Jump to content

function to alternate row colours not working


shocker-z

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
Link to comment
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
Link to comment
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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.