shocker-z Posted May 8, 2006 Share Posted May 8, 2006 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++;}?>RegardsLiam Link to comment https://forums.phpfreaks.com/topic/9308-function-to-alternate-row-colours-not-working/ Share on other sites More sharing options...
kenrbnsn Posted May 8, 2006 Share Posted May 8, 2006 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 https://forums.phpfreaks.com/topic/9308-function-to-alternate-row-colours-not-working/#findComment-34273 Share on other sites More sharing options...
shocker-z Posted May 8, 2006 Author Share Posted May 8, 2006 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 alotLiam Link to comment https://forums.phpfreaks.com/topic/9308-function-to-alternate-row-colours-not-working/#findComment-34284 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.