You get a bonus - 1 coin for daily activity. Now you have 1 coin

Alternative syntax for PHP control structures

Lecture



You probably already know how to insert HTML code into the script body. To do this, simply close the bracket ?> , The code , and then open it again with <? and continue the program.
You may have noticed how ugly it looks. However, if you make a little effort to design, everything will not be so bad. Especially if you use the alternative syntax of if-else and other language constructs.
Most often you need to do not insert HTML into the script, and insert the code inside the html . It is much easier for the designer, who may in the future want to re-draw the script, but will not be able to figure out what to change and what not to touch. Therefore, it is advisable to separate the HTML code from the program (script), for example, place it in a separate file, which is then connected to the script using the include construct. Here, for example, will look like a script that greets a user by name, using the alternative if-else syntax:

<?if(@$ name ):?>
Привет, <?=$ name ?> !
<?else:?>
<form action=<?=$REQUEST_URI?> method=get>
Ваше имя: <input type=text name=name><br>
<input type=submit value= "Отослать!" >
<?endif?>

Agree that even a person who is not at all familiar with PHP, but who is well versed in HTML, can easily understand what is happening in this scenario. Consider the alternative syntax for some constructions in the context of using it in conjunction with HTML:

Alternative syntax for if-else

A general view of the alternative syntax for an if-else is:

<?if (логическое_выражение):?>
...HTML-код...
<?else (другое_логическое_выражение):?>
...HTML-код...
<?endif?>

Alternative syntax for while loop

<?while (логическое_выражение):?>
...HTML-код...
<?endwhile;?>

An example of using alternative syntax for a while loop :

<?while($ x < 10 ):?>
<h2> <? echo $ x ;   $ x ++;?> </h2>
<?endwhile;?>

Alternative syntax for for loop

<?for(инициализирующие_команды; условие_цикла; команды_после_прохода):?>
...HTML-код...
<?endfor;?>

An example of using alternative syntax for a for loop:

<?for($ z = 1 ;$ z <= 10 ;$ z ++):?>
<h2> <? echo $ z ;?> </h2>
<?endfor;?>

As we can see, the use of alternative syntax allows you to make PHP scripts readable in cases where you need to actively operate PHP together with HTML code.

created: 2016-01-25
updated: 2021-03-13
167



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)