PHP elseif statements; separate elseif, or compressed into one? - php

I'm basically wondering if there's a difference between enumerating all the possible conditions via separate elseif statements or combining them into one (apart from readability, that is).
Example 1:
if($x == 0)
{
(condition A)
}
elseif($x == 1)
{
(condition A)
}
elseif($x == 2)
{
(condition A)
}
else
{
(condition B)
}
Example 2:
if($x == 0 || $x == 1 || $x == 2)
{
(condition A)
}
else
{
(condition B)
}
Obviously example 2 is more readable, but is it also faster (or otherwise preferred)?

The cleanest option I've seen for your code is the following:
switch($x) {
case 0:
case 1:
case 2:
(condition A)
break;
default:
(condition B)
break;
}

You could also do:
if ($x <= 2) {
// Condition A
} else {
// Condition B
}
But to answer your question:
Of the 2 statements, theoretically the second would be faster but only because PHP would be parsing 1 statement recursively rather than 3 separate statements. However, the difference is so minuscule that you probably won't be able to accurately measure it. Which means they may as well be identical. My answer above this text would be faster than either of the supplied example because there is only 1 comparison (not 3). But again, the difference is small enough that it may as well be the same.

No, they're functionally equivalent.

Related

Using just if and elseif in a php syntax

This might be a noob question. I just wanna ask if it's correct to use the following codes inside a switch statement:
case 'OPTION1':
if ($_SESSION['session2'] == 'cart') {
$code = '1567';
}
else if($_SESSION['session2'] == 'online') {
$code= 'A90f';
}
break;
Or do I always have to add an else at the end of every if elseif statements? Thank you!
You only need to add an else and as many else ifs as makes sense in the code, so your example is fine.
Sometimes you may want to add some default behaviour (just the same as in a switch()) which covers the - it didn't match anything else...
if ($_SESSION['session2'] == 'cart') {
$code = '1567';
}
else if($_SESSION['session2'] == 'online') {
$code= 'A90f';
}
else {
$code = '';
}
But you could alternativelty say
$code = '';
if ($_SESSION['session2'] == 'cart') {
$code = '1567';
}
else if($_SESSION['session2'] == 'online') {
$code= 'A90f';
}
The OP's question concerns the basics of PHP, a worthwhile subject for review whatever one's expertise may be. While a switch statement may prove useful for avoiding messy looking long if-statements, the OP's code contains a switch statement with only one case that contains itself an if control structure. So, while the syntax is correct, the switch statement appears superfluous since the if control structure could just as easily execute without being embedded in a switch statement.
As far as the usage concerning else, that provides for default code to execute in the case of one or more if-statements evaluating as false. Also, note that the else if code only evaluates when the preceding if condition returns false. To illustrate:
<?php
$a = 3;
$b = 5;
if ($a == $b) {
echo '$a and $b are equivalent';
}
else
if ($a > $b) {
echo '$a is greater than $b';
}
else
{
echo 'The rain in Spain stays mainly in the plain';
}
?>
See live code and read more here
You could optionally recode the preceding example using a switch statement as follows:
<?php
$a = 3;
$b = 5;
switch($a) {
case ($b):
echo '$a and $b are equivalent';
break;
case ($a > $b):
echo '$a is greater than $b';
break;
default:
echo 'The rain in Spain stays mainly in the plain';
break;
}
?>
See live code
With respect to the switch statement the Manual notes:
In many occasions, you may want to compare the same variable (or
expression) with many different values, and execute a different piece
of code depending on which value it equals to. This is exactly what
the switch statement is for.
#Nigel's answer is fine. I'd just add that I'll rather use elseif instead of else if for PSR-2 compliance: https://www.php-fig.org/psr/psr-2/
The behaviour between else if and elseif is just the same.

IF vs. SWITCH and which is more suitable for this job and why?

I'm wondering whether it is possible to replicate this kind of check in a switch statement/case:
if(isset($_POST["amount"]) && (isset($_POST["fruit"]))) {
$amount = $_POST['amount'];
$fruit = $_POST['fruit'];
if($fruit == "Please select a fruit") {
echo "<script>alert('Required Field: You must choose a fruit to receive your total')</script>";
} else if(empty($fruit) or ($amount<=0) or ($amount>50)) {
echo "<script>alert('Required Field: You must enter an amount between 0-50g to receive your total')</script>";
} ... and further on
Note: I'm paying more attention to the && comparison that can be done simply in one IF, and whether this is possible to be done in a switch case and receive results like the nested if/else would. If it's not possible, why? and which method would be more efficient and why?
I would rather stick with If-Else If condition rather than converting it to Switch statement.
You have to realize the the switch statement only accepts one parameter:
switch($arg)
In your case you have amount as $_POST["amount"] and fruit as $_POST["fruit"].
Your first problem is how will you pass that 2 values on the switch statement.
You cannot use a switch for this case, since you are checking a condition (isset) of two variables which produces a boolean result. Well actually you could do a switch of this condition and switch in case of true to this code and in case of false to that code. But that would not make much sense imho.
In a switch you can just check ONE variable or expression and in the cases you execute the code of whatever the result of that switch evaluation was.
So no, you cannot do a switch with these nested ifs.
edit: to make this a bit more clear, a swicth is best used when you find yourself using multiple ifs on the same variable:
if ($var < 3)
{
// do this
}
elseif ($var < 6)
{
// do that
}
else
{
// do something other
}
Would be much better written:
switch ($var)
{
case < 3:
// do this
break;
case < 6:
// do that
break;
default:
// do somehting other
}

PHP Nested Ifs vs Single If with Multiple Conditions [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
php multiple if conditions
What is better ? Multiple if statements, or one if with multiple conditions
So I was working on a segment of code in which I ended up using two different styles of if statements. That got me wondering - which one is more efficient in PHP? Are there times when one might be better than the other, despite general differences (if present)? Is there a certain level of complexity where the benefits become clear (if close) or close (if originally clear)? Also, are there other benefits of one method over the other, other than aesthetic or subjective differences?
if ($value == 'someval') {
if($otherval == 'someval') {
// do stuff
} else if ($otherval == 'otherval') {
// do same stuff
}
}
vs
if (($value == 'someval') && ($otherval == 'someval' || $thirdval == 'someval') {
// do stuff
}
Note - I don't care what works for C# or Java or whatever other language, unless someone can show that they handle the construct exactly the same.
So long as you're executing the same code in each block (as you've indicated by your comments) then they'll both do the trick (and no, there's really not much of a performance difference).
However, typically it's not the case that you'd execute the same code both ways, so logically the first block is actually different from the second in that case. Here's an example:
if($value == 'someval') {
if($otherval == 'someval') {
doSomething();
}
else if ($otherval == 'otherval') {
doSomethingElse();
}
}
versus:
if(($value == 'someval') && ($otherval == 'someval' || $otherval == 'otherval')) {
//we now still need to evaluate $otherval in order to determine which func to execute...
//this adds bloat...
if($otherval == 'someval') {
doSomething();
}
else if ($otherval == 'otherval') {
doSomethingElse();
}
}
So as you can see in the case above the second block is actually less efficient than the first.
There is no real difference, you should use whichever is more readable.
Nested or not nested if-blocks?

Programmimg Logic

Am new to the world of coding and have difficulty is understanding the logic below. Appreciate it if someone could explain it to me. Let me start off with If statements.
/* Sample Code */
if($username == "123") {
//some code here;
}
if ($username == "abc") {
//some code here;
}
My understanding is that IF the first statement fails, progress to the second statement i.e. if $username does not equal to 123 then test whether it is abc. Is that correct?
Now, let me expand on that same code with else statements
/* Sample Code */
if($username == "123") {
//some code here;
}
if ($username == "abc") {
//some code here;
}
else {
//some code here;
}
My understanding is that IF the first staement FAILS i.e. $username does not equal to 123 then test the second statement. IF the second statement fails i.e. $username does not equal to abc then proceed to ELSE which is a catchall should all preceding IF statements FAIL. Is that correct?
Let me expand on that again using ELSE IF statements
/* Sample Code */
if($username == "123") {
//some code here;
}
else if ($username == "abc") {
//some code here;
}
else {
//some code here;
}
How is this code different from 2 separate if statements? What does ELSE do in the entire block of code?
the difference between:
if() {
}
else if() {
}
and
if() {
}
if() {
}
is that the second condition in the second example is always tested, regardless of the first if condition. In the first example, the second clause only executes if the first clause is false.
In your example, since "123" is never equal to "abc", they are equivalent. In real life, the ifs don't need to be related:
if (a) {
// Do something
} else if (b) {
// Do something else
} else {
// Do something else
}
is different from
if (a) {
// Do something
}
if (b) {
// Do something else
} else {
// Do something else
}
In the second case, both a and b might be true, in which case both lines will fire. In the first case, only the first line will fire, since the else will never even be read.
In this case they are the same:
if($username == "123") {
//some code here;
}
if ($username == "abc") {
//some code here;
}
against
if($username == "123") {
//some code here;
}
else if ($username == "abc") {
//some code here;
}
The difference is that with else if if the first case is true the second case will never fire.
e.g.
if($username == "123") {
//some code here;
$username = "abc"
}
if ($username == "abc") {
//some code here;
}
Both code if statement code blocks will be executed where as in:
if($username == "123") {
//some code here;
$username = "abc"
}
else if ($username == "abc") {
//some code here;
}
only the first if statement code block will be executed.
You aren't right, here's how it works:
if($something == "something")
{
//code
}
if($something == "somethingelse")
{
//code
}
Both of the above will be tested regardless of what $something equals, because they are two separate if statements. So if you were to do:
$something = "something";
if($something == "something")
{
echo $something;
}
$something = "somethingelse";
if($something == "somethingelse")
{
echo $something;
}
then the output would be "somethingsomethingelse" because both are tested. Note that in an if/elseif/else structure, it would be a syntax error to put a line of code between the ending of one block and the beginning of another.
if($something == "something")
{
//code
}
else
{
//code
}
In this, the first statement will be tested, if it is true, then it will run through that code. If false, then the code in the else block will occur.
if($something == "something")
{
//code
}
elseif($something == "somethingelse")
{
//code
}
else
{
//code
}
In this it would check the first if statement, if true, then that code runs. If false, it checks the elseif statement, if true it runs that. If false it runs the else block. The else block is a catch all.
So in something like:
if(false)
{
//code
}
elseif(false)
{
//code
}
else
{
//code
}
the else block will always be run.
The same sort of thing occurs in multiconditional statements such as:
if(is_string($something) && $something == "something")
if is_string($something) is false, it won't check the second condition because they both must be true when AND is used, and if is_string($something) is true and $something == "something" is false, then the entire if condition is false, yet again because they both must be true.
if($something == "something" || $something == "somethingelse")
In this OR statement, it will check both if the first is false, because one or the other must be true in order for the if statement to be true. So if $something does equal "somethingelse" then the if statement will be considered true. However, if $something does equal "something" then the second condition won't be checked, because it already got the true condition it needs to make the statement true.
So an && condition in an if condition is like doing:
if(is_string($something))
{
if($something == "something")
{
//code
}
}
and and || statement is like doing:
if($something == "something")
{
//code
}
elseif($something == "somethingelse")
{
//same code as previous if statement
}
Here is an example:
//this would be pulled from a page called like:
//http://www.domain.com/page.php?num=5&num2=10
$num = $_GET['num']; //5
$num2 = $_GET['num2']; //10
if(!is_numeric($num))
{
echo 'Number 1 is not a number, cannot continue <br />';
}
elseif(!is_numeric($num2))
{
echo 'Number 2 is not a number, cannot continue <br />';
}
else
{
if($num > $num2)
{
echo 'Number 1 is bigger than Number 2 <br />';
}
elseif($num2 > $num)
{
echo 'Number 2 is bigger than Number 1 <br />';
}
else
{
echo 'Numbers are equal <br />';
//Since if the numbers are neither greater than or less than each other, they must be equal to one another
}//end if
//% is the modulo operator, basically returns the remainder of division
//so !($num % $num2) is if the remainder of $num / $num2 == 0, I.E. NOT(!) $num % $num2
//! basically makes it take the opposite of the result, so !(0) is true, and 0 is false
//in the same way !(true) is literally NOT true (in other words false)
//and !(false) is literally NOT false (true)
if(!($num % $num2))
{
echo 'Number 1 is a multiple of Number 2 <br />';
}
else
{
echo 'Number 1 is not a multiple of Number 2 <br />';
}//end if
if(!($num2 % $num))
{
echo 'Number 2 is a multiple of Number 1 <br />';
}
else
{
echo 'Number 2 is not a multiple of Number 1 <br />';
}//end if
echo 'The sum of the numbers is ' . $num + $num2;
}//end if
So, with this, and an input of num=5&num2=10, the output would be
Number 2 is bigger than Number 1
Number 1 is not a multiple of Number 2
Number 2 is a multiple of Number 1 //Note that both of the multiple conditions were tested, because they are separate
The sum of the numbers is 15
With this an an input of num=16&num2=3, the output would be:
Number 1 is bigger than Number 2
Number 1 is not a multiple of Number 2
Number 2 is not a multiple of Number 1
The sum of the numbers is 19
and with an input of num=16&num2=word, the only output would be
Number 2 is not a number, cannot continue
and with an input of num=4&num2=4 the output would be
Numbers are equal
Number 1 is a multiple of Number 2
Number 2 is a multiple of Number 1
The sum of the numbers is 8
My understanding is that IF the first
statement fails, progress to the
second statement i.e. if $username
does not equal to 123 then test
whether it is abc. Is that correct?
This isn't correct. Both expressions will be evaluated; however, at most one of them can be true. Your third example behaves the way you describe above.
In your second example, if $username == "123", then the block associated with the first if statement will execute; however, the "else" block associated with the second if statement will also execute.
In the first example, both "if" statements are executed. If both are true, both happen.
In your case, both can't be true, but that's no reason not to use "else". If nothing else [no pun intended], "else" will provide a semantic hint for future programmers that you're only expecting one of the two clauses to be true.
The only way for your statement:
IF the first statement fails, progress to the second statement
to be true is if the second statement was indeed in an "else" clause of the first statement.
Only in the last snippet does the code behave as you describe. When you have an if followed by a second if, both tests are performed. There is no symbiosis or relation in the code flow.
if(X1){
A;
}elseif(X2){
B;
}elseif(X3){
C;
}else{
D;
}
this means: if X1 evaulates to true then do A. If not look if X2 evaluates to true. if yes do B. if not look if X3 evaluates to true. if so do C. if not then just do D.
if(X1){
A;
}
if(X2){
B;
}
this means: if X1 evaluates to true do A. end of your first if. then another if comes: if X2 evaluates to true then do B. these two if statements are separated from eachother unlike my first example.
the alternative if syntax in php makes it a bit clearer:
My first example in alternative syntax:
if(X1):
A;
elseif(X2):
B;
elseif(X3):
C;
else:
D;
endif;
my second example:
if(X1):
A;
endif;
if(X2):
B;
endif;
here you see clearly that these two if statements are separated from eachother.

Is this the way to do this simple IF OR OR statement?

I have an if statement with a few or's in it.
i.e.
if($count == 1 || $count == 3 || $count == 7) {
// do stuff
}
I'm just curious - is this the best way to do this? With this simple example above, is there a faster way to do this, and if so, what is it?
Your code works fine. Alternately, you can use in_array(), which is a bit cleaner and scales better:
if (in_array($count, array(1,3,7))) { ... }
The code you've written is fine. As Paul Schreiber says, there are various other options that are a little neater.
One thing you may want to think about (and I know this is just an example) is why the values you're checking are important. Do they all have some property in common that you're checking? If so, then stating the property symbolically may make the code easier for someone to understand. For example:
if (is_odd($x) && $x < 10) {
//...
}
rather than
if ($x == 1 || $x == 3 || $x == 5 || $x == 7 || $x == 9 ) {
//...
}
This is quite a contrived example, but hopefully you see what I'm getting at.
As a more concrete example, instead of doing something like:
if ($user->age > 65
|| $user->years_of_custom > 3
|| $num_items > 5 ) {
// Give this user a discount ....
}
you might want to do:
if (eligible_for_discount($user, $num_items) ) {
// Give this user a discount
}
Even if you only use the function in this one place, this could increase the readability of the code. Obviously you have to use your judgment though, because you're increasing readability at the expense of having more lines of code to maintain, and that isn't always the right choice. If the conditions have little to do with each other, binding them up into a separate function might make no sense and make your code harder to follow, not easier. Focus on what your code actually means, and how a human being should understand it.
You can assign all possible value in an array and check using array_search function
$array=array(1,3,7);
if (array_search($count,$array) !== FALSE)
{
//do stuff
}
Wouldn't the switch statement be better?
switch ($count) {
case 1:
case 3:
case 7:
echo "do stuff";
break;
}

Categories