/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] alternating row colors

In addition to using the modulus operator, you can use a static variable within a function alternate row colors:

[code=php]
function setClass(){
static $setClass=’darkBg’;
$setClass=$setClass==’darkBg’?’lightBg’:’darkBg’;
return $setClass;
}
[/code]

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@bokehAug 09.2006 — Simpler[code=php]function setClass(){
static $i = 0;
return ($i ^= 1) ? 'lightBg' : 'darkBg';
}[/code]
But really I believe using a function for something so basic is overkill. The only benefit I see is keeping the variable out of the global scope (which may be helpful depending on context).
Copy linkTweet thisAlerts:
@sitehatcheryauthorAug 09.2006 — I believe using a function for something so basic is overkill[/quote]

actually, quite handy here when you have multiple rows dynamically generated:
[code=php]
<style type="text/css">
.lightBg{background-color:red; width:150px; height:10px;}
.darkBg{background-color:blue; width:150px; height:10px;}
</style>

<?php
function setClass(){
static $i = 0;
return ($i ^= 1) ? 'lightBg' : 'darkBg';
}

for($i=0; $i<10; $i++){
?>
<div class="<?php echo setClass(); ?>"></div>
<?php } ?>
[/code]


I'm trying to understand how your code ($i ^= 1) acheived this result. Can you explain this?
Copy linkTweet thisAlerts:
@bokehAug 09.2006 — ^ is [URL=http://www.php.net/manual/en/language.operators.bitwise.php]PHP's XOR bitwise operator[/URL] but the manual description is not too easy to follow. A bitwise exclusive OR takes two bit patterns of equal length and performs the logical XOR operation on each pair of corresponding bits. The result in each position is 1 if the two bits are different, and 0 if they are the same. Put in simple language it switchs [I]$i[/I] to the opposite state. So if the value of [I]$i[/I] was [I]zero[/I] it would be switched to [I]one[/I] and vice versa as demonstrated by the following. [code=php]<pre>

<?php

$i = 0;

for($j = 0; $j < 10; $j++)
{
var_dump($i ^= 1);
}

?>[/code]
×

Success!

Help @sitehatchery spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...