Jump to content


Photo

Break it down for me


  • Please log in to reply
2 replies to this topic

#1 sdaniels

sdaniels
  • Members
  • PipPipPip
  • Advanced Member
  • 46 posts

Posted 18 April 2006 - 04:53 AM

Im using this code for a table on one of my pages, it alternated the background color for each table row

only thing about it is that I dont see how it is switching the color,

i understand that it is saying

$bg = '#FFFFCC'; //iIget this part, color = whatever before loop
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { //I also get this
$bg = ($bg=='#FFFFCC' ? '#ffffff' : '#FFFFCC'); 
// OK now I dont get it, were saying that bg equals bg if it equals ffffcc... i dont unerstand the '?' and i dont understand the colon. why is this code able to switch the color?
echo '<tr bgcolor="' . $bg . '">

basicly if someone could put this in english for me...


an example of what i mean is if i was asking about this code

if (isset($foo)) { echo 'hi'; }

Id like to understand it as, if a variable named foo has a value then print out the word hi

#2 ypirc

ypirc
  • Members
  • PipPipPip
  • Advanced Member
  • 54 posts

Posted 18 April 2006 - 05:08 AM

That's called a ternary operator. [a href=\"http://us3.php.net/manual/en/language.operators.comparison.php\" target=\"_blank\"]http://us3.php.net/manual/en/language.oper....comparison.php[/a]

Here's a short example for you to understand.

$a = 1;

$b = ($a == 1) ? 2 : 0;


Basically, it is testing if "$a == 1", if true, set $b = 2, else set $b equal to 0.

So, in your code it's saying if $bg equals to '#FFFFCC' set $bg to '#ffffff', otherwise, set it to '#FFFFCC'.

#3 sdaniels

sdaniels
  • Members
  • PipPipPip
  • Advanced Member
  • 46 posts

Posted 18 April 2006 - 05:20 AM

[!--quoteo(post=365886:date=Apr 18 2006, 12:08 AM:name=ypirc)--][div class=\'quotetop\']QUOTE(ypirc @ Apr 18 2006, 12:08 AM) View Post[/div][div class=\'quotemain\'][!--quotec--]
That's called a ternary operator. [a href=\"http://us3.php.net/manual/en/language.operators.comparison.php\" target=\"_blank\"]http://us3.php.net/manual/en/language.oper....comparison.php[/a]

Here's a short example for you to understand.

$a = 1;

$b = ($a == 1) ? 2 : 0;


Basically, it is testing if "$a == 1", if true, set $b = 2, else set $b equal to 0.

So, in your code it's saying if $bg equals to '#FFFFCC' set $bg to '#ffffff', otherwise, set it to '#FFFFCC'.
[/quote]


ah ha, I see, so thats why each time through the loop $bg has a different value... so it sets the color then changes the value.... Thanks, I can wrap my mind around it now that you have explained it.

OK to better understand for myself, could I do this and get the same result?
$bg = '1';
if ($bg == '1''{ $bg = '2'; } else { $bg = '1'; }





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users