I've got a question about isset() with multiple conditionals, and checking to make sure they return non-null or correct results.
I'm trying to troubleshoot an isset expression that looks like:
if(isset($content['field_1']) && $content['field_2'] && $content['field_3']=="top"){
do a thing
}
I understand that if field_1 is true, then the other conditionals are treated as true.
My "if" statement is looped thorugh a few times as a slideshow is being created.
Most of the slide created have all true resuults and are fine, but there are a couple slides where the value exists but not exactly as required.
The code works, but the drupal error log gets filled warnings of "undefined index".
The question I have is:
What is the best way to have a multiple conditional isset while proofing each section?
a simple "else" after the "if" isn't solving this since it's multiple conditionals (I think). and I don't know if there is an easier way to handle this than breaking the multiple conditionals into single ones before continuing.
If anyone kind enough to read this has questions, or if my question is not clear pelase let me know. I'm happy to clarify.
Thanks!
I understand that if field_1 is true, then the other conditionals are treated as true.
Your assumption is wrong. You do not check value of $content referenced by key field_1, you check if such key exsits - these are two different things. Also you use && (AND) operator, and in such case if one condition returns false then evaluating remaining is pointless as by the boolean logic the whole expression will be false.
try this:
if ((!empty($content['field_1']) || !empty($content['field_2'])) && !empty($content['field_3']) && $content['field_3'] == 'top') {
// Do Something
}
Related
I want to try and make my code as efficient as possible and from what ive read
if($process == true)
Will process faster than something that calls a function. I.e
if(count($total) == 100)
So if i had an OR inside my if and the first condition was a simple boolean check and it turned out to be true would the second part of the condition still be checked anyway?
For example
$process = true;
if($process == true || count($total) == 100)
Would the count function still be called even though process is true and that is enough the make the condition pass.
PHP has indeed a mechanic named short-circuit:
http://php.net/manual/en/language.operators.logical.php#example-140
If the first operand of a logical OR is true, then the second part isn't evaluated, and the function isn't called.
Since comparing a variable to a boolean is faster than calling a function in PHP, this mechanic can help you to optimize, but never forget that premature optimisation is the root of all evil.
It will work same as exactly logical operator works. For example foo() will never get called.
if (false && foo()) {
}
if (true || foo()) {
}
In case of OR once it found a true statement it wont check further conditions,
In case of AND once it found a false statement it wont check further conditions.
its known as lazy evaluation.
illustration:
<?php
$var=0;
if($var++ || $var++){//Since 0 means false in Php both conditions will be checked
//Do nothing
}
echo $var;//output :2
if we change condition to if(++$var || $var++) the first condition will return true hence next condition will not be checked thus it will print output as 1;
If any statement inside a or is true other statements will not be checked and the if will be evaluated to true.
If you are checking a and statement all statements needs to evaluate to true and if any of them is false the stamen check will stop because the if is already false.
Just another important detail is that a function inside a if does not slow down the if check, what will slow down is what the function is doing and if it needs a lot of processing of course will be slower than just check a boolean but do not get afraid of use functions because they are very important in any system.
(I remember this from C# but I'm quite sure it's the same in php)
This depends if you use the single | or double || I think if you used the single ones it would still go do the other one ( usefull for when theres a function like loggin behind it ) if you use double and the first one is true it'll skip the second condition.
(This could be the other way around, so best bet is to try it using Javascript eg. create 2 function each returning true after alerting something, and thest these with either 1 line or 2)
I have a conditional statement in php, when I add an OR logical operator it doesn't work as intended, in the below example it returns the code that I am trying to prevent it doing.
Individually each statement works just not when they are together as I have them below. It seems inefficient to repeat the code for each condition.
if (!is_sp_post_type('profile') || !is_category(array('previews','reviews')) || !is_single(array('previews','reviews'))) {
//do stuff
};
I have read this answer Is there a short-circuit OR in PHP that returns the left-most value? but I'm still stuck
Just make use of the AND (&&) operator.
The OR operator just needs one true to execute the conditional, whereas the AND operator needs all statement to be true.
I'm not hundred percent sure what you are trying to achieve, but I would also suggest having a re-look at your NOT (!) operator and how it is used in your code
I was being silly, should have been using &&
if (!is_sp_post_type('profile') && !in_category(array('previews','reviews')) && !is_single(array('previews','reviews'))) {
//do stuff
}
Thanks to Pieter Goosen for pointing this out - he deleted his answer though so I cannot select it.
I actually found out how to solve this particular problem on my own, but it's still driving me crazy wondering why the problem came about to begin with. I had a conditional statement:
if($_SESSION['authenticated'] = 1) {
DOSTUFF;
}
Now prior to this if statement I know that $_SESSION['authenticated'] is empty by using print_r(). However, after executing this code block this conditional statement assigns 1 to $_SESSION['authenticated'], which makes the if statement evaluate to true no matter what! I found a way around this using isset(), but I still have no clue why a conditional statement would assign a value to a variable in the first place when it should only evaluate whether or not the condition is true or false.
Because = is assignment. You want == or === which test for equality. === checks that the operands are both equal and of the same type. == only checks for equality.
You have a semantic (or syntactic) (or typing) error. You should use double equal sign for equality comparison like this:
if($_SESSION['authenticated'] == 1) {
DOSTUFF;
}
If you use single equality sing, that means assignment, and the assigned value gets evaluated in the if statement.
I have a PHP script that runs through an array of values through my own custom function that uses the PHP function preg_match. It's looking for a match with my regular expression being $valueA, and my string to search being $valueB, and if it finds a match, it returns it to $match, otherwise I don't want my IF statement to run.
Now, I'm having no problem with this IF statement running if the function finds a match (in other words, is TRUE);
if ($match = match_this($valueA, $valueB))
{
//do this
}
HOWEVER, if I wanted to compare an additional condition to check if it is also TRUE, and only run the IF statement when both are TRUE, I run into problems;
if ($match = match_this($valueA, $valueB) && $x == 'x')
{
//do this
}
Instead of the statement running as normal when both conditions are TRUE, I end up outputting a 1 from $match instead of what my $match value should be.
I can sort of see what's happening. My IF statement is just returning a literal boolean TRUE into $match, instead of my value returned from match_this();
Is this because I can only return one sense of TRUE?
I can get around the problem by having two nested IF statements, but for the sake of clean code I'd like to be able to compare multiple conditions in my IFs which includes functions that return values.
Are there different kinds of TRUE? If so, how do I compare them in this way? Or is there an easier method? I suppose I could just put a second IF statement inside my function and pass my second condition through the function, but then my function wouldn't be very clearly defined in terms of its purpose.
I've ran into this problem before and didn't quite know what I was looking for. Hope someone can help.
if (($match = match_this($valueA, $valueB)) && $x == 'x')
^ ^
You missed an extra set of brackets.
Without the extra set of brackets around $match = match_this($valueA, $valueB), the evaluation of the && is performed first and finally result is assigned to $match.
Alternatively, you could use and (which has lower precedence than assignment =) instead of &&
PHP Operator Precedence
if ($match = match_this($valueA, $valueB))
^---wrong operator
You should be using == for equality tests. Right now you're just assigning the return values of match_this. Ditto for your other if()
as per the comments below, if you actually ARE wanting to do assignments within the if() structure, then you should slap a very-large-blinking-neon-bright comment/warning above the code to say that this is intended behavior. In most any language and most any other person looking at this code later on will assume it's a typo and change the assignment to an equality test.
A simple question that could remove the need for quite a lot of if/else statements.
If, for example, I have such a query:
if ($success1=$db->query('SELECT * FROM `foo`;') || $success2=$db->query('SELECT * FROM `bar`;')) {
...
}
Would it stop checking when the first query is successful or not?
What you're referring to is called a short circuit. Yes php uses short circuits. With AND (&&) If the first check in the conditional fails, it never checks the second. The same applies for OR ( || ). If the first check succeeds it never looks at the second statement.
See the following post for verification:
PHP short circuit lazy evaluation, where is it in the php.net manual?
An example of when this is very useful is when dividing by zero. In the first check you determine if the denominator is zero, and then in the second check you do the dividing. The order is important. If the denominator is zero it will skip the second check and will never divide by zero.
if($x != 0 && 10/$x > 3)
If the first one is true, then it will not need to check anything else in the statement so it will carry on. If not, code like this:
if(isset($var) && $var == 1)
Would never work as it would throw up a not defined error. As soon as it sees the first one is false, it stops the rest of the statement.