if statements or if then elseif?

Soldato
Joined
7 Jan 2007
Posts
10,607
Location
Sussex, UK
Hi guys in PHP should you do this:

if (condition)
(
code
}

if (condition)
{
code
}

else
{
do this
}

OR IS this the correct way:

if (condition)
{
code
}

elseif (condition)
{
code
}

else
{
code
}


I only ask as I have done the first example and some scripts work, others don't seem to work for all statements.
 
If the variables to be tested are of the same type and the condition is just 'value = x' , use a switch. Otherwise, if/elseif.

Although it does depend on the logic flow you want. For example, if/elseif will only hit the first matching condition. Separate if statements will hit all conditions.
 
It depends on what the condition is.

In this first example both 'if' statements could be executed if their conditions are true. In the second example even if the condition of the 'elseif' is true it wont be executed if the preceding 'if' statement was executed.

There is no right answer here, it completely depends on what you want the code to do.
 
the logic is different between the two isnt it?

the second statement may only test one condition, the first will always test at least 2
 
I'll have to post the logic up tonight. Sounds like the problem may not be my code, it could be that cron job didn't work or simply the XML I scrape wasn't updated on that day.

I'm going to test it another week.
The logic runs on a day of the week and checks for numerical values and compares against the previous line in the db.

I'm 90% sure the source XML wasn't updated
 
Use the if....elseif...else statement to select one of several blocks of code to be executed.

Syntax:

if (condition)
{
code to be executed if condition is true;
}
elseif (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

Example:

<html>
<body>

<?php
$d=date("D");
if ($d=="Fri")
{
echo "Have a nice weekend!";
}
elseif ($d=="Sun")
{
echo "Have a nice Sunday!";
}
else
{
echo "Have a nice day!";
}
?>

</body>
</html>
 
Back
Top Bottom