METANIT.COM

PHP : Better way to print html in if-else conditions

My question is which one of the following is a better option.I know the second one is more readable. But if there are so many conditions on the same page, then which is better performance-wise(i believe, there will be only a negligible performance difference between the two). I would like to know your views/points, regarding standards performance and whatever you think I should know, about the two different forms. (And which should be preferred over the other,when there is only single if-else block, and multiple if-else blocks) Thanks

Better would be to no inject HTML via PHP. Use a proper framework to this for you. softwareengineering.stackexchange.com/a/180504/211576

Ideally you wouldn’t be constructing your pages this way, because it’s an antipattern. However if you must pick between the two, historically I’ve always seen the first done, though I don’t know the reasons behind it.

2 Answers 2

I would argue that the first example is the better of the two evils as it is more maintainable. The HTML is written as is, and not coded as a string literal.

Using templating or some other way to keep business logic and HTML presentation separate usually results in more maintainable code.

As always, the short and probably most correct answer: It depends.

For the two snippets in that short as shown in the question it’s purely about taste. There is no strong technical reason for one over the other. In a larger context the question is «are those rather HTML templates with a little logic in between or are those code parts with lot’s of logic and a little of HTML?»

Of course if it’s mostly logic, a good idea is to look into template library’s like Twig or others and separate the logic from output in a larger degree, whcih allows testing and changing output formats more easily.

Источник

PHP if else

Summary: in this tutorial, you’ll learn about the PHP if. else statement that executes a code block when a condition is true or another code block when the condition is false .

Introduction to PHP if-else statement

The if statement allows you to execute one or more statements when an expression is true :

 if ( expression ) < // code block >Code language: HTML, XML (xml)

Sometimes, you want to execute another code block if the expression is false . To do that, you add the else clause to the if statement:

 if ( expression ) < // code block > else < // another code block >Code language: HTML, XML (xml)

In this syntax, if the expression is true , PHP executes the code block that follows the if clause. If the expression is false , PHP executes the code block that follows the else keyword.

The following flowchart illustrates how the PHP if-else statement works:

The following example uses the if. else statement to show a message based on the value of the $is_authenticated variable:

 $is_authenticated = false; if ( $is_authenticated ) < echo 'Welcome!'; > else < echo 'You are not authorized to access this page.' >Code language: HTML, XML (xml)

In this example, the $is_authenticated is false . Therefore, the script executes the code block that follows the else clause. And you’ll see the following output:

You are not authorized to access this page.Code language: JavaScript (javascript)

PHP if…else statement in HTML

Like the if statement, you can mix the if. else statement with HTML nicely using the alternative syntax:

 if ( expression ): ?>  else: ?>  endif ?>Code language: HTML, XML (xml)

Note that you don’t need to place a semicolon ( ; ) after the endif keyword because the endif is the last statement in the PHP block. The enclosing tag ?> automatically implies a semicolon.

The following example uses the if. else statement to show the logout link if $is_authenticated is true . If the $is_authenticated is false , the script shows the login link instead:

html> html lang="en"> head> meta charset="UTF-8"> title>PHP if Statement Demo title> head> body>  $is_authenticated = true; ?>  if ($is_authenticated) : ?> a href="#">Logout a>  else: ?> a href="#">Login a>  endif ?> body> html>Code language: HTML, XML (xml)

Summary

Источник

PHP if

Summary: in this tutorial, you’ll learn about the PHP if statement and how to use it to execute a code block conditionally.

Introduction to the PHP if statement

The if statement allows you to execute a statement if an expression evaluates to true . The following shows the syntax of the if statement:

 if ( expression ) statement;Code language: HTML, XML (xml)

In this syntax, PHP evaluates the expression first. If the expression evaluates to true , PHP executes the statement . In case the expression evaluates to false , PHP ignores the statement .

The following flowchart illustrates how the if statement works:

PHP if flowchart

The following example uses the if statement to display a message if the $is_admin variable sets to true :

 $is_admin = true; if ($is_admin) echo 'Welcome, admin!';Code language: HTML, XML (xml)

Since $is_admin is true , the script outputs the following message:

Curly braces

If you want to execute multiple statements in the if block, you can use curly braces to group multiple statements like this:

 if ( expression ) < statement1; statement2; // more statement >Code language: HTML, XML (xml)

The following example uses the if statement that executes multiple statements:

 $can_edit = false; $is_admin = true; if ( $is_admin ) < echo 'Welcome, admin!'; $can_edit = true; >Code language: HTML, XML (xml)

In this example, the if statement displays a message and sets the $can_edit variable to true if the $is_admin variable is true .

It’s a good practice to always use curly braces with the if statement even though it has a single statement to execute like this:

 if ( expression ) Code language: HTML, XML (xml)

In addition, you can use spaces between the expression and curly braces to make the code more readable.

Nesting if statements

It’s possible to nest an if statement inside another if statement as follows:

 if ( expression1 ) < // do something if( expression2 ) < // do other things > >Code language: HTML, XML (xml)

The following example shows how to nest an if statement in another if statement:

 $is_admin = true; $can_approve = true; if ($is_admin) < echo 'Welcome, admin!'; if ($can_approve) < echo 'Please approve the pending items'; > >Code language: HTML, XML (xml)

Embed if statement in HTML

To embed an if statement in an HTML document, you can use the above syntax. However, PHP provides a better syntax that allows you to mix the if statement with HTML nicely:

 if ( expession) : ?>  endif; ?>Code language: HTML, XML (xml)

The following example uses the if statement that shows the edit link if the $is_admin is true :

html> html lang="en"> head> meta charset="UTF-8"> title>PHP if Statement Demo title> head> body>  $is_admin = true; ?>  if ( $is_admin ) : ?> a href="#">Edit a>  endif; ?> a href="#">View a> body> html>Code language: HTML, XML (xml)

Since the $is_admin is true , the script shows the Edit link. If you change the value of the $is_admin to false , you won’t see the Edit link in the output.

A common mistake with the PHP if statement

A common mistake that you may have is to use the wrong operator in the if statement. For example:

 $checked = 'on'; if( $checked = 'off' ) < echo 'The checkbox has not been checked'; >Code language: HTML, XML (xml)

This script shows a message if the $checke d is ‘off’ . However, the expression in the if statement is an assignment, not a comparison:

$checked = 'off'Code language: PHP (php)

This expression assigns the literal string ‘off’ to the $checked variable and returns that variable. It doesn’t compare the value of the $checked variable with the ‘off’ value. Therefore, the expression always evaluates to true , which is not correct.

To avoid this error, you can place the value first before the comparison operator and the variable after the comparison operator like this:

 $checked = 'on'; if('off' == $checked ) < echo 'The checkbox has not been checked'; >Code language: HTML, XML (xml)

If you accidentally use the assignment operator (=), PHP will raise a syntax error instead:

 $checked = 'on'; if ('off' = $checked) < echo 'The checkbox has not been checked'; >Code language: HTML, XML (xml)
Parse error: syntax error, unexpected '=' . Code language: JavaScript (javascript)

Summary

  • The if statement executes a statement if a condition evaluates to true .
  • Always use curly braces even if you have a single statement to execute in the if statement. It makes the code more obvious.
  • Do use the pattern if ( value == $variable_name ) <> to avoid possible mistakes.

Источник

Php if condition in html

Условные конструкции позволяют направлять работу программы в зависимости от условия по одному из возможных путей. И одной из таких конструкций в языке PHP является конструкция if..else

Конструкция if..else

Конструкция if (условие) проверяет истинность некоторого условия, и если оно окажется истинным, то выполняется блок выражений, стоящих после if. Если же условие ложно, то есть равно false, тогда блок if не выполняется. Например:

0) < echo "Переменная a больше нуля"; >echo "
конец выполнения программы"; ?>

Блок выражений ограничивается фигурными скобками. И так как в данном случае условие истинно (то есть равно true): значение переменной $a больше 0, то блок инструкций в фигурных скобках также будет выполняться. Если бы значение $a было бы меньше 0, то блок if не выполнялся.

Если блок if содержит всего одну инструкцию, то можно опустить фигурные скобки:

0) echo "Переменная a больше нуля"; echo "
конец выполнения программы"; ?>

Можно в одной строке поместить всю конструкцию:

if($a>0) echo "Переменная a больше нуля";

В данном случае к блоку if относится только инструкция echo «Переменная a больше нуля»;

else

Блок else содержит инструкции, которые выполняются, если условие после if ложно, то есть равно false:

 0) < echo "Переменная a больше нуля"; >else < echo "Переменная a меньше нуля"; >echo "
конец выполнения программы"; ?>

Если $a больше 0, то выполняется блок if, если нет, то выполняется блок else.

Поскольку здесь в обоих блоках по одной инструкции, также можно было не использовать фигурные скобки для определения блоков:

if($a > 0) echo "Переменная a больше нуля"; else echo "Переменная a меньше нуля";

elseif

Конструкция elseif вводит дополнительные условия в программу:

Можно добавить множество блоков elseif . И если ни одно из условий в if или elseif не выполняется, тогда срабатывает блок else.

Определение условия

Выше в качестве условия применялись операции сравнения. Однако в реальности в качестве условия может применяться любое выражение, а не только такое, которое возвращает true или false . Если передаваемое выражение равно 0, то оно интерпретируется как значение false . Другие значения рассматриваются как true :

if (0) <> // false if (-0.0) <> // false if (-1) <> // true if ("") <> // false (пустая строка) if ("a") <> // true (непустая строка) if (null) <> // false (значие отсутствует)

Альтернативный синтаксис if

PHP также поддерживает альтернативный синтаксис для конструкции if..else , при которой вместо открывающей фигурной скобки ставится двоеточие, а в конце всей конструкции ставится ключевое слово endif .

$a = 5; if($a > 0): echo "Переменная a больше нуля"; elseif($a < 0): echo "Переменная a меньше нуля"; else: echo "Переменная a равна нулю"; endif;

Комбинированный режим HTML и PHP

Также мы можем написать конструкцию if..else иным образом, переключаясь внутри конструкции на код HTML:

       0) < ?>

Переменная a больше нуля

?>

В данном случае само условие указывется в отдельном блоке php: 0) < ?>. Важно, что при этом этот блок содержит только открывающую фигурную скобку "

Завершается конструкция if другим блоком php, который содержит закрывающую фигурную скобку: ?>

Между этими двумя блоками php располагается код, который отображается на html-странице, если условие в if истинно. Причем этот код представляет именно код html, поэтому здесь можно разместить различные элементы html, как в данном случае элемент

При необходимости можно добавить выражения else и elseif :

       0) < ?>

Переменная a больше нуля

elseif($a < 0) < ?>

Переменная a меньше нуля

else < ?>

Переменная a равна нулю

?>

Также можно применять альтернативный синтаксис:

       0): ?> 

Переменная a больше нуля

Переменная a меньше нуля

Переменная a равна нулю

Тернарная операция

Тернарная операция состоит из трех операндов и имеет следующее определение: [первый операнд - условие] ? [второй операнд] : [третий операнд] . В зависимости от условия тернарная операция возвращает второй или третий операнд: если условие равно true , то возвращается второй операнд; если условие равно false , то третий. Например:

Если значение переменной $a меньше $b и условие истинно, то переменная $z будет равняться $a + $b . Иначе значение $z будет равняться $a - $b

Источник

Читайте также:  Php что такое datetime
Оцените статью