I am just wondering if there is better way to solve my situatuion:
I have 6 independent variables to check. But if any of conditions is true it shouldnt check other. Normally I would write:
if (cond1 ) {
statement
} else {
if ( cond2 ) {
statement
} else {
if (cond3) {
statement
} else {
...
}
}
}
Surely you would admit it doesnt look good or it is not easy to read although it works. Do you know any other ways to write such if statement maybe using other notation or functions (switch? while?)
Yes, you can do
if (cond1 ) {
statement
} elseif ( cond2 ) {
statement
} elseif ( cond3 ) {
statement
}
See documentation
A more stylish way:
if(cond1):
statement1
elseif(cond2):
statement2
elseif(cond3):
statement3
elseif(cond4):
statement4
elseif(cond5):
statement5
elseif(cond6):
statement6
endif;
This is how you do it with a switch():
$a = 10;
$b = 100;
switch(true){
case ($a > $b):
echo 'a is bigger than b';break;
case ($b > $a):
echo 'b is bigger than a';break;
}
if (cond1 ) {
statement
} else {
if ( cond2 ) {
statement
} else {
if (cond3) {
statement
} else {
...
}
}
}
Change to:
if (Cond1){
}elseif (cond2){
}elseif (cond3){
}
Related
I am in the making of some code that needs to check if a users login details are correct, and I therefore need a lot of if-statements inside each other. If any of the conditions in the if-statements are not true, they should alle return the same value. Is there an easy way of doing this, instead of writing the same multiple times? I have made an example below to visualize my problem. As you can see here I write " else { return false; }" multiple time, and this is what I am wondering if you are able to do more efficiently. Maybe so I only have to write "or else return false" once.
//some code
if (/*some condition*/) {
//some code
if (/*some new condition*/) {
//some code
if (/*some new condition*/) {
//some code
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
I am having a hard time finding a good way to explain my problem, so if you have a more elegant way of explaining it, do not hesitate to edit my post. I am also not quite sure that the title is as good as it could be, so if you have any ideas to an alternativ please say so :)
Lets say you have something like that (I added No):
if ( condition1 ) {
//some code 1
if ( condition2 ) {
//some code 2
if ( condition3 ) {
//some code 3
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
Since each time a condition is false, you exit the function returning false, you can directly test if the condition is false using a negation (if the negated condition is true):
if ( !condition1 ) {
return false;
}
//some code 1
if ( !condition2 ) {
return false;
}
//some code 2
if ( !condition3 ) {
return false;
}
//some code 3
This doesn't reduce the number of if statements, but you avoid many nesting levels and the else statements.
You can also try the switch statement. For many situations it will produce cleaner code.
<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
The switch statement is also compatible with using strings:
<?php
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
echo "i is bar";
break;
case "cake":
echo "i is cake";
break;
}
?>
Good luck! :)
I need to implement 3 'if conditions' in my script, i've looked it up online but I can only find solutions up to 2 if's like below
<?
if (condition 1){
do something;
}
elseif (condition 2){
do something else;
}
else {
do this last;
}
?>
but I would need something like this:
if (condition 1) { do this };
else if (condition 2) {do that};
or else if (condition 3) {do that};
else (do this)
How do I go about this?
simply
if(condition){
}
else if(condition){
}
else if(condition){
}
else{
}
you can use switch case statements too. you can use else if as many as you want. Each condition inside if() can accept OR and AND operators as || for OR and && for AND you can use.
if (condition 1) { do this
} else if (condition 2) {do that
} else if (condition 3) {do that
} else { do this }
alternatively if you want to check one variable each time you can use a switch for example
$myvar = 5;
switch($myvar){
case 1:
//do this
break;
case 2:
//do that
break;
case 3:
//do that
break;
default:
//do this
}
You can use this construction
if ( $a == $b ) {
// something...
} else if ( $a == $c ) {
// something...
} else if ( $a == $d ) {
// something...
} else {
// otherwise...
}
But if all of the conditions are ( $a equals to something ) it's better to use switch ... case:
switch ( $a ) {
case $b:
// something...
break;
case $c:
// something...
break;
case $d:
// something...
break;
default:
// otherwise...
break;
}
Solution 1
Using many elseif statements as you want.
Use this solution when your conditions are complex, or comparing different variables.
if (/*condition 1*/) {
// Action to condition 1
} else if (/*condition 2*/) {
// Action to condition 2
} else if (/*condition 3*/) {
// Action to condition 3
} else if (/*condition n*/) {
// Action to condition n
} else {
// Action when no conditions match.
}
Solution 2
Using switch statement:
Use this condition when you want to compare a variable against constant values:
switch ($age) {
case 0:
return 'You are a baby';
break;
case 18:
return 'You are 18 years old';
break;
case 21:
case 22:
case 23:
return 'You are too old';
default:
return 'Unexpected age :(';
}
How about using the or operator, ||:
if (condition 1) { do this }
else if (condition 2 || condition 3) {do that}
else {do this}
An example:
<?php
function testCondition($a, $b) {
if ($a == $b) {
print ("They are the same<br />\n");
}
else if ($a == "a" || $b == "b") {
print ("One is the same as its letter<br />\n");
}
else {
print ("They are some other sort<br />\n");
}
}
testCondition("c","c");
testCondition("a","c");
testCondition("a","b");
testCondition("d","e");
?>
Outputs:
They are the same
One is the same as its letter
One is the same as its letter
They are some other sort
I have the same problem as first stated here. I have four variables but the second one is skipped and only 1,3, and 4 work. Why?
if(empty($fromName) or empty($fromEmail) or empty($subject) or empty($comments)) {
echo 'You cannot submit the form with empty fields. Please correct the form and resubmit.';
return false;
}
elseif($fieldDelete == "Delete this text!"){
echo "Delete the contents of the fourth field before submitting.";
return false;
}
elseif (($fromName == "Curtisvien") || ($fromName == "Thomastymn") || ($fromName == "RichardMark")) {
echo "Failed. Please try again.";
return false;
}
else {
$flgchk = mail ("$to", "$subject", "$message", "$headers");
$imgfile = "images/NatMap logo2.gif";
$handle = fopen($filename, "r");
$imgbinary = fread(fopen($imgfile, "r"), filesize($imgfile));
echo '<img src="data:image/gif;base64,' . base64_encode($imgbinary) . '" width=427 height=72 />';
echo "\n<br />\n<br />Thank You! An e-mail has been sent to the National Map web team and they will get back to you in the next 24-48 hours.";
}`enter code here`
I am using the following code to pass a variable. if variable = a, do nothing.
I then want to check if variable = a, do nothing, if b, do nothing, else do something
<?
if($_GET['pageid'] == 'a'){
} else {
include('header_image.php');
}
?>
Above is the code I have working correctly for one vartiable.
How do I add an if / else?
if($_GET['pageid'] != 'a' && $_GET['pageid'] != 'b'){
//do smth
}
This is a comment - i want the formatting...
To do what you want:
if ($_GET['pageid'] == 'a') {
// do nothing for now
}
elseif ($_GET['pageid'] == 'b') {
// do some more nothing...
}
else { // we do something...
include('header_image.php');
}
You could combine the 'do nothing' tests as:
if ( $_GET['pageid'] == 'a'
|| $_GET['pageid'] == 'b') {
// do nothing for now
}
else { // we do something...
include('header_image.php');
}
I agree it reads better than the 'not equal and' tests. However, that is what 'programmers' use so it is worthwhile getting used to it.
This should be a simple question. I have a simple if/else statement:
<?php
// TOP PICTURE DEFINITIONS
if ( is_page('english') ) {
$toppic = 'page1.png';
}
if ( is_page('aboutus') ) {
$toppic = 'page1.png';
}
if ( is_page('newspaper') ) {
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
?>
Is there a difference from ^^^ to this:
<?php
// TOP PICTURE DEFINITIONS
if ( is_page('english') ) {
$toppic = 'page1.png';
}
elseif ( is_page('aboutus') ) {
$toppic = 'page1.png';
}
elseif ( is_page('newspaper') ) {
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
?>
I should mention that this is going into Wordpress. And until now, I've used the first part (no elseif, just a series of 'ifs'), and it works. I was just curious to know what the difference was.
Thanks!
Amit
Yes. If a condition in an if/else control is satisfied, the rest of the checks will be omitted. else if is just a nested if inside an else!
if ( is_page('english') ) { // if true, other statements are skipped
$toppic = 'page1.png';
}
elseif ( is_page('aboutus') ) {
$toppic = 'page1.png';
}
elseif ( is_page('newspaper') ) {
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
But in a series of ifs, all of them will be tested.
if ( is_page('english') ) {
$toppic = 'page1.png';
}
if ( is_page('aboutus') ) { // will be tested no matter what the outcome
// of the previous if statement was
$toppic = 'page1.png';
}
if ( is_page('newspaper') ) { // the same here
$toppic = 'page1.png';
}
else {
$toppic = 'page1.png';
}
So, if you're checking a property such as parity of a number, it's either odd or even, why do you want to bother checking other conditions if one is satisfied. It's a waste of resources. Therefore, the following code is much better
if(number_is_odd) {
}
else { // if it's not odd, it's even for sure
}
than
if(number_is_odd) {
}
if(!number_is_odd) {
}
Because the former checks the condition once whilst the latter does it twice. The same thing goes for conditions with more than two states.
The first method will check against every condition, whether they are true or false.
The second method will check against every condition until one is true, and then ignores the rest.
In your first block, every comparison in your block is executed. Also, toppic will always be assigned the value in is_page('newspaper') or the value in is_page('newspaper')'s else statement. This happens because the last if statment is always evaluated. Even if one of the previous if statements evaluated to true, you'll end up in the else block. To test this, try this code...
<?php
// TOP PICTURE DEFINITIONS
if ( is_page('english') ) {
$toppic = 'english.png';
}
if ( is_page('aboutus') ) {
$toppic = 'aboutus.png';
}
if ( is_page('newspaper') ) {
$toppic = 'newspaper.png';
}
else {
$toppic = 'finalelse.png';
}
?>
You'll always end with either 'newspaper.png' or 'finalelse.png'.
<?php
if ( 3 > 1 ) {
echo "This will be printed.";
}
if ( 3 > 2 ) {
echo "This will be printed too.";
}
if ( 3 > 3 ) {
echo "This will NOT be printed.";
}
else {
echo "This WILL be printed.";
}
?>
but with elseif:
<?php
if ( 3 > 1 ) {
echo "This will be printed.";
}
elseif ( 3 > 2 ) { /* This condition will not be evaluated */
echo "This will NOT be printed";
// because it's on the ELSE part of the previous IF
}
elseif ( 3 > 3 ) { /* This condition will not be evaluated either */
echo "This will NOT be printed.";
}
else { /* This ELSE condition is still part of the first IF clause */
echo "This will NOT be printed.";
}
?>
So you should use ELSEIF, because otherwise $toppic will always result on either 'newspaper.png', wich should be right, or 'finalelse.png' wich could be right or wrong, because it will overwrite the previous conditional clauses.
I hope you'll find this helpful.
It's not always just a question of efficiency. If you are toggling something, it is essential to use else if and not just if
Let's say we are toggling the variable $computerOn
if ($computerOn == true) {
$computerOn = false;
}
if ($computerOn == false) {
$computerOn = true;
}
In the case above your $computerOn will always be true. If it's true, it is set to false. After this, we check if it is false, which it now must be independent of initial conditions, so it is now set to true.
On the other hand the code below will toggle $computerOn:
if ($computerOn == true) {
$computerOn = false;
} elseif ($computerOn == false) {
$computerOn = true;
}
Now we only check whether $computerOn is false if it was not initially true. Hence we have a toggle.
If things get more complicated, you might have to use multiple elseifs. It's important to recognize when logic dictates that elseif is a must vs an option.
The biggest difference between the two is that the very last else block will be called whenever is_page('newspaper') returns false. In this case, it means just about every time the script runs. In this case, it's not a big deal, since you're only setting a variable, and it's the same value as everything else. But, if it were different, you would have a very frustrating bug to track down!
Besides that, if you use separate if statements, the condition for each if is evaluated every time. Again, in this case, it's (probably) not a big deal. But, if the condition was, say...
if(delete_file('foo.png')) {
....
}
if(delete_file('bar.png')) {
....
}
if(delete_file('baz.png')) {
....
}
else {
....
}
Well, you should be able to see where this is going ;) If you use elseif, it will stop trying to evaluate once it gets a true. And, the else will only be called if nothing else is true.
The answer is simple:
if(a==1){
b
}
elsif(b==1){
c
}
equals to
if(a==1){
b
}
else{
if(b==1){
c
}
}
This is the same as
if(a==1){
b
}
if(b==1){
c
}
if it is not possible that a==1 and b==1 at the same time. Although when both if statements can be true, when b and c can be executed. This would not be possible if you use elsif there, because b==1 would only be checked if a!=1!
Use elseif wisely can save you a bunch of time since the parser doesn't need to evaluate all the conditions.
How does PHP read if statements?
I have the following if statements in this order
if ( $number_of_figures_in_email < 6) {
-- cut: gives false
}
if($number_of_emails > 0) {
-- cut: gives false
}
if ( $number_of_emails == 0) {
-- cut: gives true
}
The code behaves randomly. It sometimes goes to the third if clause and gives me a success, while sometimes to the one of the first two if clauses when the input variables are constant.
This suggests me that I cannot code only with if statements.
It doesn't "behave randomly", it does what you tell it to do:
if ($a) {
// do A
}
if ($b) {
// do B
}
if ($c) {
// do C
}
All three ifs are independent of each other. If $a, $b and $c are all true, it'll do A, B and C. If only $a and $c are true, it'll do A and C, and so on.
If you're looking for more "interdependent" conditions, use if..else or nested ifs:
if ($a) {
// do A and nothing else
} else if ($b) {
// do B and nothing else (if $a was false)
} else if ($c) {
// do C and nothing else (if $a and $b were false)
} else {
// do D and nothing else (if $a, $b and $c were false)
}
In the above only one action will get executed.
if ($a) {
// do A and stop
} else {
// $a was false
if ($b) {
// do B
}
if ($c) {
// do C
}
}
In the above both B and C might get done, but only if $a is false.
This, BTW, is pretty universal and not at all PHP specific.
If you want to return only one of the results from many different if statements, use elseif, like this:
if ( $number_of_figures_in_email < 6) {
-- cut: gives false
}
elseif($number_of_emails > 0) {
-- cut: gives false
}
elseif ( $number_of_emails == 0) {
-- cut: gives true
}