ExpressionEngine PHP Segment Conditionals

This is from an old wiki article at the previous domain.  There are a number of inbound links to it, so I’m reproducing its content here:

Uses: Input Class
Requires: PHP Parsing on Input, if used in a Template.
Advantages: The template parsing engine will not parse any tags except those inside of conditionals that evaluate as TRUE, as opposed to ExpressionEngine advanced conditionals () where everything is parsed before the conditional is evaluated.

This example checks to see if the first URL segment is either “salsa”, “pico”, or something else entirely.

  1. <?php
  2. global $IN;
  3.  
  4. if ($IN->fetch_uri_segment('1') == 'salsa'): ?>
  5. You like it spicy!
  6. <?php elseif ($IN->fetch_uri_segment('1') == 'pico'): ?>
  7. You like it fresh!
  8. <?php else: ?>
  9. You don't like it!
  10. <?php endif; ?>
  11.  

Note that you can assign the segments to variables first, making it easy to use multiple URI segments in your PHP conditionals.  The following code assigns URI segments 1 and 2 to variables, and then checks to see that a third segment exists AND that the second segment is ‘foo’:

  1. <?php
  2. global $IN;
  3.  
  4. $seg1 = $IN->fetch_uri_segment('1');
  5. $seg2 = $IN->fetch_uri_segment('2');
  6.  
  7. if (($seg3 != '' && $seg2 == 'foo'): ?>
  8. Yep!
  9. <?php endif; ?>
  10.