Php if print else print

print

print — это не функция, а языковая конструкция. Его аргумент — это выражение после ключевого слова print , не ограниченное круглыми скобками.

Главное отличие от echo в том, что print принимает только один аргумент и всегда возвращает 1 .

Список параметров

Выражение для вывода. Нестроковые значения будут преобразованы в строки, даже если включена директива strict_types .

Возвращаемые значения

Примеры

Пример #1 Примеры использования print

print «print не требует скобок.» ;

// Новая строка или пробел не добавляются; ниже выводит «приветмир» в одну строку
print «привет» ;
print «мир» ;

print «Эта строка занимает
несколько строк. Новые строки
также будут выведены» ;

print «Эта строка занимает\nнесколько строк. Новые строки\nтакже будут выведены» ;

// Аргументом может быть любое выражение, производящее строку
$foo = «пример» ;
print «пример — это $foo » ; // пример — это пример

$fruits = [ «лимон» , «апельсин» , «банан» ];
print implode ( » и » , $fruits ); // лимон и апельсин и банан

// Нестроковые выражения приводятся к строковым, даже если используется declare(strict_types=1)
print 6 * 7 ; // 42

// Поскольку print имеет возвращаемое значение, его можно использовать в выражениях
// Следующие выходные данные «привет мир»
if ( print «привет» ) echo » мир» ;
>

// следующее выражение выведет «true»
( 1 === 1 ) ? print ‘true’ : print ‘false’ ;
?>

Примечания

Замечание: Использование с круглыми скобками

Заключение аргумента print в круглые скобки не вызовет синтаксической ошибки и создаст синтаксис, который выглядит как обычный вызов функции. Однако это может ввести в заблуждение, поскольку круглые скобки на самом деле являются частью выводимого выражения, а не частью самого синтаксиса print .

print( «привет» );
// также выведет «привет», потому что («привет») — корректное выражение

print( 1 + 2 ) * 3 ;
// выведет «9»; круглые скобки приводят к тому, что сначала вычисляется 1+2, а затем 3*3
// оператор print видит все выражение как один аргумент

if ( print( «привет» ) && false ) print » — внутри if» ;
>
else print » — внутри else» ;
>
// выведет » — внутри if»
// сначала вычисляется выражение («привет») && false, давая false
// это приводится к пустой строке «» и выводится
// конструкция print затем возвращает 1, поэтому выполняется код в блоке if
?>

Читайте также:  Folder directory in java

При использовании print в более крупном выражении может потребоваться размещение ключевого слова и его аргумента в круглых скобках для получения желаемого результата:

if ( (print «привет» ) && false ) print » — внутри if» ;
>
else print » — внутри else» ;
>
// выведет «привет — внутри else»
// в отличие от предыдущего примера, выражение (print «привет») вычисляется первым
// после вывода «привет» print возвращает 1
// поскольку 1 && false ложно, выполняется код в блоке else

print «привет » && print «мир» ;
// выведет «мир1»; print «мир» выполняется в первую очередь,
// тогда выражение «привет» && 1 передается в левую часть print

(print «привет » ) && (print «мир» );
// выведет «привет мир»; круглые скобки заставляют выражения print
// выполнятьтся перед &&
?>

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций или именованных аргументов.

Смотрите также

  • echo — Выводит одну или более строк
  • printf() — Выводит отформатированную строку
  • flush() — Сброс системного буфера вывода
  • Способы работы со строками

Источник

Php if print else print

Часто необходимо выполнить одно выражение, если определённое условие верно, и другое выражение, если условие не верно. Именно для этого else и используется. else расширяет оператор if , чтобы выполнить выражение, в случае, если условие в операторе if равно false . К примеру, следующий код выведет a больше чем b , если $a больше, чем $b , и a НЕ больше, чем b в противном случае:

Выражение else выполняется только, если выражение if вычисляется как false , и если нет других любых выражений elseif , или если они все равны false также (смотрите elseif).

Замечание: Болтающийся else

В случае вложенных операторов if — else , else всегда ассоциируется с ближайшим if .

Несмотря на отступ (который не имеет значения в PHP), else связан с if ($b) , поэтому этот пример ничего не выведет. Хотя такое поведение допустимо, рекомендуется его избегать, используя фигурные скобки для устранения потенциальных неоднозначностей.

Читайте также:  Java jframe on exit event

User Contributed Notes 10 notes

An alternative and very useful syntax is the following one:

statement ? execute if true : execute if false

Ths is very usefull for dynamic outout inside strings, for example:

print(‘$a is ‘ . ($a > $b ? ‘bigger than’ : ($a == $b ? ‘equal to’ : ‘smaler than’ )) . ‘ $b’);

This will print «$a is smaler than $b» is $b is bigger than $a, «$a is bigger than $b» if $a si bigger and «$a is equal to $b» if they are same.

If you’re coming from another language that does not have the «elseif» construct (e.g. C++), it’s important to recognise that «else if» is a nested language construct and «elseif» is a linear language construct; they may be compared in performance to a recursive loop as opposed to an iterative loop.

$limit = 1000 ;
for( $idx = 0 ; $idx < $limit ; $idx ++)
< $list []= "if(false) echo \" $idx ;\n\"; else" ; >
$list []= » echo \» $idx \n\»;» ;
$space = implode ( » » , $list );| // if . else if . else
$nospace = implode ( «» , $list ); // if . elseif . else
$start = array_sum ( explode ( » » , microtime ()));
eval( $space );
$end = array_sum ( explode ( » » , microtime ()));
echo $end — $start . » seconds\n» ;
$start = array_sum ( explode ( » » , microtime ()));
eval( $nospace );
$end = array_sum ( explode ( » » , microtime ()));
echo $end — $start . » seconds\n» ;
?>

This test should show that «elseif» executes in roughly two-thirds the time of «else if». (Increasing $limit will also eventually cause a parser stack overflow error, but the level where this happens is ridiculous in real world terms. Nobody normally nests if() blocks to more than a thousand levels unless they’re trying to break things, which is a whole different problem.)

There is still a need for «else if», as you may have additional code to be executed unconditionally at some rung of the ladder; an «else if» construction allows this unconditional code to be elegantly inserted before or after the entire rest of the process. Consider the following elseif() ladder:

Читайте также:  How to switch java version

Источник

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.

Источник

Оцените статью