Community

Snippets with if and else statements

I am trying to write a spinet with if and else statements. However, when I try to load my page I am getting an error. An example of my code is below. The idea is to have two snippets, the first of which ends after if($var == ‘Whatever’):
How can I do this?

<?php
  if($var == 'Whatever'):

  else:
      if($var == 'Something Else'):

      endif;
  endif;
?>

Typically you’d use this syntax in PHP:

<?php
if($var == 'Whatever') { 
   // do something
}
elseif ($var == 'Something Else') {
  // do something else
}

$var does have to be defined.

1 Like

Thank you for your quick reply. I think I found the problem with my snippet was twofold.
First, like you said, my syntax was off. Second, I was trying to echo HTML from within my snippet. Below is my final, working code. Thanks again :slight_smile:

        <?php
        $var = 'Whatever';
        if($var == 'Whatever') { 
           $props = array(
            'cow' => 'Moo',
            'pig' => 'Oink',
            );
        }
        elseif ($var == 'Something Else') {
           $props = array(
            'cow' => 'Hello',
            'pig' => 'World',
            );
        }
        return $modx->getChunk('myChunk', $props);
3 Likes