PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
robshanks wrote:
But the second example executes all three if statements even if the first is true.
One could understand this as "all if statetments are considered true" ...
@shivam0101
1. The usage of these statements depends higlhy on the context you are using it in. I could never tell what's best for you without having the surrounding code.
2. You could use "elseif" keyword instead of "else if".
There are 10 types of people in this world, those who understand binary and those who don't
<?php
$cond = '';
if (!empty($_POST['cond'])) {
$cond = $_POST['cond'];
switch ($cond) {
case 'insert':
//insert statement
break;
case 'edit':
//edit statmement
break;
case 'delete':
//delete statement
break;
default:
// default if $cond is not one of these
}
?>
The reason it "works" is because it's not possible for those if statements to overlap. Using else and else if makes PHP not need to check all of the statements if one of them is true before it reaches the last one.
if ($action == "submit_edit")
{
// do some validation
if (!$dataLookingGood)
{
$action = "do_edit";
}
// do update
}
if ($action == "do_edit")
{
// print Edit Form and fill it.
}
There are 10 types of people in this world, those who understand binary and those who don't
How is that good? PHP will have to actually run an if evaluation on both of them, even though one or the other is false. In an if else statement, if the if fires true, then the else is not evaluated. Less resource use is good.
Sometimes it is very efficient to use "side effects". Yes, it is really very dangerous, nasty program flow, etc.
The example above is just like using switch without break in one or more case statements.
There are 10 types of people in this world, those who understand binary and those who don't
VladSun wrote:Sometimes it is very efficient to use "side effects". Yes, it is really very dangerous, nasty program flow, etc.
The example above is just like using switch without break in one or more case statements.
I disagree. I would reword that and say, "Sometimes it is very efficient to not take shortcuts and write code the correct way and not worry about very dangerous, nasty logic etc. The example above is a programmer not using object oriented code to solve a problem".