ifs and buts

ifs and buts

Post by ooo shiny » Sun, 01 Jan 2006 20:40:39


I have been studying the php and mysql for dummies book trying to understand
the if statement. It tells you what it is and how it is used but doesnt really
give enough examples of why it is used. I have just got the php 5 for dummies
today thinking it would give more info about it but is really the same. Can
anyone give me a few examples of the if statement in different situations? Just
need a few examples so I can get up and running and move onto else and other
statements.
 
 
 

ifs and buts

Post by Michael Fe » Mon, 02 Jan 2006 01:18:48

.oO(ooo shiny red ball)


What is unclear?

You use it if you want to check a certain condition and perform
different actions dependent on the result. The condition can be nearly
anything, it can be a check of a user-submitted value, a check of a
calculated result, a complex calculation itself, a call to another
function, whatever, as long as the result is a logical TRUE or FALSE:

if (something is TRUE) then
do something

or

if (something is TRUE) then
do this
else
do that

(pseudo-code)


if ($monday) {
print 'Bad day.';
}

// check for user-submitted variable 'foo', isset returns TRUE or FALSE
if (isset($_GET['foo'])) {
print 'found';
} else {
print 'not found';
}

// check for existence of a certain file
$filename = '...';
if (file_exists($filename)) {
// do something with the file
} else {
// show error message or something else
}

// calculate factorial of $n
function fac($n) {
if ($n < 2) {
return 1;
} else {
return $n*fac($n-1);
}
}

// print ten table rows with alternating background color
for ($i = 0; $i < 10; $i++) {
// '%' is the modulo operator, it devides the first by the second
// argument and returns the rest. In this case the rest is always
// either 1 or 0, which are equal to TRUE and FALSE due to PHP's
// automatic type conversion. If $i is even, the rest is 0 and the
// condition FALSE, if it's odd, the rest is 1 and the condition TRUE.
if ($i % 2) {
print "<tr>\n";
} else {
print "<tr class='colored'>\n";
}

...

print "</tr>\n";
}

Micha