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.
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 am checking if two values are null. If both are null I want to return false, if either or both are not null, I want to return true.
My current code returns true only when both are not null but I want it to return true when either or not null.
// check if both null
if (!isset($myarray['dataone'], $myarray['datatwo']))
{
echo 'false';
);
} else {
echo 'true';
);
}
return $emptytabs;
For that you can use relational operators. AND (&&) OR (||)
By using AND (&&) operators.
if ( (!isset($myarray['dataone']) || (!isset$myarray['datatwo'] ))
{
echo 'false';
}
else
{
echo 'true';
}
By using OR ( || ) operators.
if (isset($myarray['dataone'] && isset$myarray['datatwo'])
{
echo 'false';
}
else
{
echo 'true';
}
// check if both null
if ( !isset($myarray['dataone']) && !isset($myarray['datatwo'])) {
echo 'false';
} else {
echo 'true';
}
// check if one or both are null
if ( !isset($myarray['dataone']) || !isset($myarray['datatwo'])) {
echo 'false';
} else {
echo 'true';
}
// check if both null
if ( !isset($myarray['dataone'], $myarray['datatwo']) )
{
echo 'false';
} else {
echo 'true';
}
return $emptytabs;
this approach you provided is totally true , but it only return true if all the provided parameters are set according to php documentations .
so your code should works correctly . except you have unwanted parentheses that should deleted
The simplest way is to use the OR (||) operator. You want to show 'true' if one thing is set OR another thing is set. Just say that with code.
if ( isset($myarray['dataone']) || isset($myarray['datatwo']) ) {
echo 'true';
} else {
echo 'false';
}
Using the AND operator adds pointless complexity by checking that both of the two things are not set in order for it to show 'false'. That's not an intuitive way to think about it, so it doesn't make sense to write the code that way.
DISCLAIMER: This answer is opinionated.
EDIT : Damn... It was all about Path to the file and somehow I didn't thought about restructuring :| thanks to #Machavity I found the problem.
What is wrong with this code ?
If $foo is set and file exist file_exist() result should be 1.
else if $foo is set but file does not exist file_exist() result should be 2.
else result should be 3.
But I am only getting result 2 for all the three conditions. There gotta be something wrong with the second part of the elseif.
if ( isset ( $foo ) && file_exists ( 'bar.php' ) )
{
echo '1';
}
else if ( isset ( $foo ) && ( ! file_exists ( 'bar.php' ) ) )
{
echo '2';
}
else
{
echo '3';
}
Normally I don't like wrapping but try restructuring like this. This way you have a better idea of what's failing
if(isset($foo)) {
if(file_exists('bar.php')) {
echo '1';
} else {
echo '2';
}
} else {
echo '3';
}
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){
}
Somewhere along the line I'm adding or leaving out a { } but I just can't figure out where
<?php
if (file_exists('config.php')) {
require_once('config.php');
{
if ( $EDITED_CONFIG == false )
{
header("Location: welcome.php");
}
}
}
else (file_exists('default-config-new.php')) {
require_once('default-config-new.php');
{
if ( $EDITED_CONFIG == false )
{
header("Location: welcome.php");
}
}
}
?>
If file exists require it and if edited = false redirect, if true end script.
else
If file exists require it and if edited = false redirect, if true end script.
So if the first file doesn't exist it mustn't require it or look for edited, it must skip to the second file and if that exists it must checked edited and then if is false then redirect. If the first file is true it must end script and load page. So it mustn't check second file if first file is true.
Also is this the lightest way to do this?
Thanks
If you indent your code properly, your error will become evident.
A few links that may be useful:
Wikipedia: Indent style
How to indent code
PHP Coding standard: Indentation
You're not closing your if statements: Should be something like:
<?php
if (file_exists('config.php')) {
require_once('config.php');
if ($EDITED_CONFIG == false) {
header("Location: welcome.php");
}
}
else{
require_once('default-config-new.php');
if ($EDITED_CONFIG == false) {
header("Location: welcome.php");
}
}
?>
Edited. Also, you need to close brackets around all code to be executed for that statement, before you can use another elseif or else statement:
if ($x == 1) {
echo "X is 1!";
}
else if ($x == 0) {
echo "X is 0!";
}
else {
echo "Not 1 or 0!";
}
You are missing the { after the else to enclose what you want inside the "else" block i believe
You need to write
else if (conditions...)
You have got
else (conditions...)