Forum Moderators: coopster
I have copied the start of the code from a comment in the online PHP manual. My script works great but obviously it is bad programming, as I'm doing nothing if the number is odd!
if ($year & 1) {} else {echo "</tr>";} I've looked at operators in the manual but it doesn't say how some of them work in practice, and I am not big on maths.
Sorry to ask such a basic question. I am sure there is a simple answer.
if ($year % 2 == 0) {
// year is even
} else {
// year is odd
}
the "%" is called a "MOD" operator. "a%b" returns the remainder of "a/b". if a is even, the remainder of a/2 is 0. If a is odd, a%2 it returns 1. thus the condition "!a%2" is true if a is an even number.
that little nugget of code is very good at doing table rows in alternating colours.
good luck
dcrombie's works fine as posted just remove the else if you don't need it
if ($year % 2 == 0) {
// year is even
}
modulus [ca.php.net]
>>Not it is NOT. That still uses two statements
dcrombie's works fine as posted just remove the else if you don't need it
if ($year % 2 == 0) {
// year is even
}
Oh, I am appalled - the above has 3 lines in it, not one! (etc)
How about:
print($year%2?'odd':'even');
or you might try this gem:
function do_something_only_if_year_is_even($year){
$evenness_quotient=2;
$dividend=$year/$evenness_quotient;
if($dividend==floor($dividend)){
print("something");
}
}
(I'm in a constant battle with Java zealots who are always telling me how much better Java is than this or that (esp PHP and Perl which really annoys me) I get some small satisfaction at how much of our company is glued together by my Perl scripts (and bourne shell and PHP to a lesser extent))