Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple IF statement conditions

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.

like image 387
Martyn Shutt Avatar asked Oct 26 '12 14:10

Martyn Shutt


1 Answers

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

like image 178
Anirudh Ramanathan Avatar answered Sep 22 '22 04:09

Anirudh Ramanathan