Jump to content

Precedence In If Statements?


paulmo

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.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...