When to use IF with ENDIF?

Asked

Viewed 4,910 times

2

Under what circumstances should the:

IF(CONDICAO) :

ELSE:

ENDIF;
  • 1

    It works like keys, {}.

  • Syntax Alternative for control structures https://secure.php.net/manual/en/control-structures.alternative-syntax.php#control-Structures.Alternative-syntax

  • So it’s just a different way to work with if?

  • exact, just an alternative syntax

  • I got it, vlw brother.

2 answers

2

Normally the keys { } are used to delimit the scope of a given code block.

<?php
    //sintaxe normal
    if (expressão) {
       //código php
    }

    //sintaxe alternativa, repare no uso dos : e da palavra endif
    if (expressão) :
       //codigo php
    endif
?>

Structures of Alternative Controls

Control structures such as if, for, foreach, and while can also be written in a simplified way. Here’s an example using foreach:

<ul>

<?php foreach($afazeres as $item): ?>

<li><?=$item?></li>

<?php endforeach ?>

</ul>

Note that there are no keys. Instead, the end key was replaced by an endforeach. Each structure listed above has a similar closing syntax: endif, endfor, endforeach, and endwhile

Note also that instead of using a semicolon for each structure (except the last one), there is the two-point sign. This is important!

Another example, using if/elseif/Else. Note the two dots:

<?php if ($username == 'Adri Silva'): ?>

   <h3>Oi Adri Silva</h3>

<?php elseif ($username == 'Leo'): ?>

   <h3>Oi Leo</h3>

<?php else: ?>

   <h3>Oi usuário desconhecido</h3>

<?php endif; ?>

OR

<?php 

if ($username == 'Adri Silva'):

   echo "Oi Adri Silva";

elseif ($username == 'Leo'):

   echo "Oi Leo";

else:

   echo "Oi usuário desconhecido";

endif; 

?>

Alternative syntax for control structures

So you might ask yourself: is there any difference, performance and such? This post addresses this issue

-2

When you want to compare something, relationships. inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.