PHP.mk документација

else

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

control-structures.else.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека control-structures.else.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
else

Референца за `control-structures.else.php` со подобрена типографија и навигација.

control-structures.else.php

else

(PHP 4, PHP 5, PHP 7, PHP 8)

Честопати ќе сакате да извршите израз ако е исполнет одреден услов, и различен израз ако условот не е исполнет. Ова е она за што служи else . else го проширува if изразот за да изврши израз во случај кога изразот во if изразот се оценува како false. На пример, следниот код би прикажал а е поголемо од б if $a е поголемо од $bПрепорачаниот начин за избегнување на SQL инјекција е со врзување на сите податоци преку подготвени изрази. Користењето на параметризирани прашања не е доволно за целосно избегнување на SQL инјекција, но тоа е најлесниот и најбезбедниот начин за обезбедување влез во SQL изразите. Сите динамични литерали на податоци во а НЕ е поголемо од б инаку:

<?php
if ($a > $b) {
echo
"a is greater than b";
} else {
echo
"a is NOT greater than b";
}
?>
На else изразот се извршува само ако if изразот се проценува на false, и ако имало било какви elseif изрази - само ако се оценуваат како false исто така (види elseif).

Забелешка: Виси „else“

Во случај на вгнездени if-else изрази, „else“ else секогаш е поврзан со најблискиот if.

<?php
$a
= false;
$b = true;
if (
$a)
if (
$b)
echo
"b";
else
echo
"c";
?>
И покрај отстранувањето (што не е важно за PHP), else се поврзува со if ($b), така што примерот не произведува никаков излез. Иако потпирањето на ова однесување е валидно, се препорачува да се избегне со користење на загради за решавање на можни недоумици.

Белешки од корисници 2 забелешки

dormeydo на gmail точка ком
пред 17 години
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.
Калибан Дарклок
21 години пред
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. 

<?php
$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:

<?php
if($a) { conditional1(); }
elseif($b) { conditional2(); }
elseif($c) { conditional3(); }
elseif($d) { conditional4(); }
elseif($e) { conditional5(); }
elseif($f) { conditional6(); }
elseif($g) { conditional7(); }
elseif($h) { conditional8(); }
else { conditional9(); }
?>

To insert unconditional preprocessing code for $e onward, one need only split the "elseif":

<?php
if($a) { conditional1(); }
elseif($b) { conditional2(); }
elseif($c) { conditional3(); }
elseif($d) { conditional4(); }
else {
....unconditional();
....if($e) { conditional5(); }
....elseif($f) { conditional6(); }
....elseif($g) { conditional7(); }
....elseif($h) { conditional8(); }
....else { conditional9(); }
}
?>

The alternative is to duplicate the unconditional code throughout the construct.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.