Jump to content

Precedence In If Statements?


paulmo
 Share

Recommended Posts

are if statements executed in order of precedence, where if condition is met, the next if statements are not executed? that is how I need the following to work:

if (in_array(strtolower($word), array('should', 'would'))) {echo //words hereif (in_array(strtolower($word), array('desperate','anxious' ))){echo //words here}if (in_array(strtolower($word), array('great', 'good'))) {echo words here}

Link to comment
Share on other sites

This is how your code looks when your indentation follows logic:

if (in_array(strtolower($word), array('should', 'would'))) {	echo //words here	if (in_array(strtolower($word), array('desperate','anxious' ))){		echo //words here	}	if (in_array(strtolower($word), array('great', 'good'))) {		echo //words here	}

I assume you simply did not paste in the final, required closing brace.What this says is that if the word matches 'should' or 'would', you will echo some words and then try to match it against 'desperate', 'anxious','great', and 'good'. Which is probably not what you want. What I think you want is this:

if (in_array(strtolower($word), array('should', 'would'))) {   echo //words here} else if (in_array(strtolower($word), array('desperate','anxious' ))){   echo //words here} else if (in_array(strtolower($word), array('great', 'good'))) {   echo //words here}

In this case, the if-conditionals will continue to test the value of $word until there is a match. When that happens, all the folling if-statements will be skipped.Notice the closing brace for ever if-block, and the use of else, which creates the "precedence" thing you mentioned.

Edited by Deirdre's Dad
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...