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?
Related
I am developing an application, and in part of the code, I think that looks ugly to me, in fact I call an API to retrieve an array of arrays, and I use a variable to determine if I need to call on all the elements of the table or on a specific elements, so here it is
foreach ($this->projects['projects'] as $project) {
if (is_array($project)) {
if (!isset($type_project)) {
$this->_doProcess($project);
}
elseif (isset($type_project) && ($type_project == $project['type_projet'])){
$this->_doProcess($project);
}
}
}
is there a method to call the method doProcess One time and take on consideration the criteria of conditions ?
You can combine the conditions quite easily, with the understanding that whatever that's evaluated after !isset($x) || ... will have isset($x) as a given. As follows:
foreach ($this->projects['projects'] as $project) {
if (is_array($project)) {
if (!isset($type_project) || $type_project == $project['type_projet'])) {
$this->_doProcess($project);
}
}
}
You could also tuck in the is_array into the same evaluation, however that'd make it a bit more obtuse to read, and as I understand your concern was simply over eliminating the extra _doProcess(). In any case, just so the options are spelled out:
foreach ($this->projects['projects'] as $project) {
if (is_array($project) && (!isset($type_project) || $type_project == $project['type_projet']) ) {
$this->_doProcess($project);
}
}
}
In fact, you could make it even more concise to score the single-statement holy grail:
foreach ($this->projects['projects'] as $project) {
is_array($project)
&& (!isset($type_project) || $type_project == $project['type_projet'])
&& $this->_doProcess($project);
}
I find the above quite readable actually, more so when split over three lines, but the masses may disagree over whether it's good practice... I find myself doing it once in a while.
This question already has answers here:
What's the difference between if and elseif?
(8 answers)
Closed 6 years ago.
I have the following functions:
if(A==B)
{
//do stuff
}
if(C==B)
{
//do stuff
}
if(A==B)
{
//do stuff
}
else if(C==B)
{
//do stuff
}
What is the difference between these two? I get the meaning of it but I have seen programmers prefer the first one instead of the 2nd one? why?
I personally prefer the 2nd one.
That's mostly a question of preference. I saw many programmers using both cases regardless of the actual function.
But correctly use the first case if you want both conditions to be chekced absolutely, the second one as a nested condition.
In the first case, both will be executed which makes it slower than the second one, as it checks only for the elseif, if the if condition is false
$var = 1;
if($var+1 ==2)
{
echo "test1";
}
if($var-0==1)
{
echo "test2";
}
if($var+1==2)
{
echo "test1";
}
else if($var-0==1)
{
echo "test2";
}
will output
test1test2test1
so we see, that number 2 ignores the elseif, which makes it faster.
In the first condition both the statements are excecuted because they are independent to each other, so all of them will be tested.
if(A==B)
{
//do stuff
}
if(C==B)
{
//do stuff
}
In second else if is just a nested if inside an else, so only one will of them will be tested, either if or elseif
if(A==B)
{
//do stuff
}
else if(C==B)
{
//do stuff
}
Not the same.
else if (C==B) will not be executed (even if C equals B) if the first condition was true.
without "else", just if (C==B) will be executed even if the first condition was true (in that case A==C :)
If only one variable is equal and need to run the same code regardless, it is better to use the first code so there is no loss of performance. But if you need to run different code depending on your variable, then the second is better.
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.
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;
}
Is this a proper way to say: if something is the case, do nothing?
if ( ($hostNameInfo == $hostNameInput) && ($hostAddressInfo == $hostAddressInput) )
{
return;
}
Update:
I'm not inside a function. :(
So the return is just nonsense.
Here is more code:
//if the input fields are equal to database values, no need to update and waste resources,hence, do nothing:
if ( ($hostNameInfo == $hostNameInput) && ($hostAddressInfo == $hostAddressInput) )
{
//do nothing
}
//If, however, (they are NOT equal and) input fields are not empty:
elseif (!empty($hostNameInput) && (!empty($hostAddressInput)))
{
//do something.
}
Thanks in advance,
MEM
For do nothing you simply can type:
function relax() {
;
}
if (($hostNameInfo == $hostNameInput) && ($hostAddressInfo == $hostAddressInput)) {
relax();
}
Maybe you should do the opposite, do something if your condition is not verified
if($hostNameInfo != $hostNameInput || $hostAddressInfo != $hostAddressInput) {
// do something
}
I assume you're inside a function in which case it does what you expect, although multiple return statements within a function can lead to confusion and a lack of readability. (Apparently I was wrong.)
Instead, I prefer to let all conditional blocks (my description for the code between in the if's {...} block) contain the relevant code, i.e., write the conditional check in such a way that the total condition evaluates to true when additional processing (sub-flow) is needed:
if ($hostNameInfo != $hostNameInput || $hostAddressInfo != $hostAddressInput) {
// do stuff, else skip
}
Furthermore, you can extract the conditional statement in order to improve both readability and simplicity of control flow:
$hostInfoEqualsInput = ($hostNameInfo == $hostNameInput && $hostAddressInfo == $hostAddressInput);
if (!$hostInfoEqualsInput) {
...
}
UPDATE (based on updated question). Consider this instead:
$fieldsAreFilled = (!empty($hostNameInput) && !empty($hostAddressInput));
$hostInfoEqualsInput = ($hostNameInfo == $hostNameInput && $hostAddressInfo == $hostAddressInput);
if ($fieldsAreFilled && !$hostInfoEqualsInput) {
...
}
ERGO
Minimize branch rate and avoid empty blocks by writing conditions you want to be met, not all the exceptions you want to ignore (subjective).
You're talking about best practices here..
One of best practice things is that routine shall have single exit point, though it is widely discussed and is up to developer/style.
UPDATE:
New answer, since the question was changed:
Don't see any reason to add additional checks if the code should run only under some circustances. To make the code more readable, you should stuck to whatever you accept as easy-maintainable, like this (or something similar):
// Do something only if required
if (($hostNameInfo != $hostNameInput) || ($hostAddressInfo != $hostAddressInput)) &&
!empty($hostNameInput) && !empty($hostAddressInput))
{
echo 'place some code here';
}
A native do_nothing() function would be very nice and readable sometimes.
To avoid stressing alerts from syntax checkers & linters, that go crazy when you have an empty if block, I use:
echo(null);
The other possibility is to throw a new exception, which you can later catch in your application.
UPDATE: not inside the function this is probably a bad idea.