Как сделать много else в php
(PHP 4, PHP 5, PHP 7, PHP 8)
Часто необходимо выполнить одно выражение, если определённое условие верно, и другое выражение, если условие не верно. Именно для этого else и используется. else расширяет оператор if , чтобы выполнить выражение, в случае, если условие в операторе if равно false . К примеру, следующий код выведет a больше чем b , если $a больше, чем $b , и a НЕ больше, чем b в противном случае:
if ( $a > $b ) echo «a больше, чем b» ;
> else echo «a НЕ больше, чем b» ;
>
?>?php
Выражение else выполняется только, если выражение if вычисляется как false , и если нет других любых выражений elseif , или если они все равны false также (смотрите elseif).
Замечание: Болтающийся else
В случае вложенных операторов if — else , else всегда ассоциируется с ближайшим if .
$a = false ;
$b = true ;
if ( $a )
if ( $b )
echo «b» ;
else
echo «c» ;
?>?php
Несмотря на отступ (который не имеет значения в PHP), else связан с if ($b) , поэтому этот пример ничего не выведет. Хотя такое поведение допустимо, рекомендуется его избегать, используя фигурные скобки для устранения потенциальных неоднозначностей.
User Contributed Notes 10 notes
15 years ago
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.
19 years ago
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:
Как сделать много else в php
(PHP 4, PHP 5, PHP 7, PHP 8)
Конструкция if является одной из наиболее важных во многих языках программирования, в том числе и PHP. Она предоставляет возможность условного выполнения фрагментов кода. Структура if реализована в PHP по аналогии с языком C:
if (выражение) инструкция
Как описано в разделе про выражения, выражение вычисляется в булево значение. Если выражение принимает значение true , PHP выполнит инструкцию , а если оно принимает значение false — проигнорирует. Информацию о том, какие значения считаются равными значению false , можно найти в разделе ‘Преобразование в булев тип’.
Следующий пример выведет a больше b , если значение переменной $a больше, чем $b :
if ( $a > $b )
echo «a больше b» ;
?>?php
Часто необходимо, чтобы условно выполнялось более одной инструкции. Разумеется, для этого нет необходимости помещать каждую инструкцию в if . Вместо этого можно объединить несколько инструкций в блок. Например, следующий код выведет a больше b , если значение переменной $a больше, чем $b , а затем присвоит значение переменной $a переменной $b :
if ( $a > $b ) echo «a больше b» ;
$b = $a ;
>
?>?php
Инструкции if могут быть бесконечно вложены в другие инструкции if , что даёт большую гибкость в организации условного выполнения различных частей программы.
Как сделать много else в php
(PHP 4, PHP 5, PHP 7, PHP 8)
elseif , as its name suggests, is a combination of if and else . Like else , it extends an if statement to execute a different statement in case the original if expression evaluates to false . However, unlike else , it will execute that alternative expression only if the elseif conditional expression evaluates to true . For example, the following code would display a is bigger than b , a equal to b or a is smaller than b :
if ( $a > $b ) echo «a is bigger than b» ;
> elseif ( $a == $b ) echo «a is equal to b» ;
> else echo «a is smaller than b» ;
>
?>?php
There may be several elseif s within the same if statement. The first elseif expression (if any) that evaluates to true would be executed. In PHP, it’s possible to write else if (in two words) and the behavior would be identical to the one of elseif (in a single word). The syntactic meaning is slightly different (the same behavior as C) but the bottom line is that both would result in exactly the same behavior.
The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to false , and the current elseif expression evaluated to true .
Note: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define if / elseif conditions, the use of elseif in a single word becomes necessary. PHP will fail with a parse error if else if is split into two words.
/* Incorrect Method: */
if ( $a > $b ):
echo $a . » is greater than » . $b ;
else if ( $a == $b ): // Will not compile.
echo «The above line causes a parse error.» ;
endif;
/* Correct Method: */
if ( $a > $b ):
echo $a . » is greater than » . $b ;
elseif ( $a == $b ): // Note the combination of the words.
echo $a . » equals » . $b ;
else:
echo $a . » is neither greater than or equal to » . $b ;
endif;
Как сделать много else в php
It may be worth specifically noting, if variable names follow some kind of «template,» they can be referenced like this:
// Given these variables .
$nameTypes = array( «first» , «last» , «company» );
$name_first = «John» ;
$name_last = «Doe» ;
$name_company = «PHP.net» ;
// Then this loop is .
foreach( $nameTypes as $type )
print $ < "name_ $type " >. «\n» ;
// . equivalent to this print statement.
print » $name_first \n $name_last \n $name_company \n» ;
?>
This is apparent from the notes others have left, but is not explicitly stated.
4 years ago
The feature of variable variable names is welcome, but it should be avoided when possible. Modern IDE software fails to interpret such variables correctly, regular find/replace also fails. It’s a kind of magic 🙂 This may really make it hard to refactor code. Imagine you want to rename variable $username to $userName and try to find all occurrences of $username in code by checking «$userName». You may easily omit:
$a = ‘username’;
echo $$a;
1 year ago
In addition, it is possible to use associative array to secure name of variables available to be used within a function (or class / not tested).
This way the variable variable feature is useful to validate variables; define, output and manage only within the function that receives as parameter
an associative array :
array(‘index’=>’value’,’index’=>’value’);
index = reference to variable to be used within function
value = name of the variable to be used within function
$vars = [ ‘id’ => ‘user_id’ , ’email’ => ‘user_email’ ];
function validateVarsFunction ( $vars )
//$vars[‘id’]=34; // define allowed variables
$user_id = 21 ;
$user_email = ’email@mail.com’ ;
echo $vars [ ‘id’ ]; // prints name of variable: user_id
echo $< $vars [ 'id' ]>; // prints 21
echo ‘Email: ‘ .$< $vars [ 'email' ]>; // print email@mail.com
// we don’t have the name of the variables before declaring them inside the function
>
?>
8 years ago
If you want to use a variable value in part of the name of a variable variable (not the whole name itself), you can do like the following:
$price_for_monday = 10 ;
$price_for_tuesday = 20 ;
$price_for_wednesday = 30 ;
$price_for_today = $< 'price_for_' . $today >;
echo $price_for_today ; // will return 20
?>
16 years ago
One interesting thing I found out: You can concatenate variables and use spaces. Concatenating constants and function calls are also possible.
define ( ‘ONE’ , 1 );
function one () <
return 1 ;
>
$one = 1 ;
$ < "foo $one " >= ‘foo’ ;
echo $foo1 ; // foo
$ < 'foo' . ONE >= ‘bar’ ;
echo $foo1 ; // bar
$ < 'foo' . one ()>= ‘baz’ ;
echo $foo1 ; // baz
?>
This syntax doesn’t work for functions:
// You’ll have to do:
$func = «php $foo » ;
$func ();
?>
Note: Don’t leave out the quotes on strings inside the curly braces, PHP won’t handle that graciously.
13 years ago
PHP actually supports invoking a new instance of a class using a variable class name since at least version 5.2
class Foo public function hello () echo ‘Hello world!’ ;
>
>
$my_foo = ‘Foo’ ;
$a = new $my_foo ();
$a -> hello (); //prints ‘Hello world!’
?>
Additionally, you can access static methods and properties using variable class names, but only since PHP 5.3
class Foo public static function hello () echo ‘Hello world!’ ;
>
>
$my_foo = ‘Foo’ ;
$my_foo :: hello (); //prints ‘Hello world!’
?>
21 years ago
The ‘dollar dereferencing’ (to coin a phrase) doesn’t seem to be limited to two layers, even without curly braces. Observe:
$one = «two» ;
$two = «three» ;
$three = «four» ;
$four = «five» ;
echo $$$ $one ; //prints ‘five’.
?>
This works for L-values as well. So the below works the same way:
$one = «two» ;
$ $one = «three» ;
$$ $one = «four» ;
$$$ $one = «five» ;
echo $$$ $one ; //still prints ‘five’.
?>
NOTE: Tested on PHP 4.2.1, Apache 2.0.36, Red Hat 7.2
21 years ago
You may think of using variable variables to dynamically generate variables from an array, by doing something similar to: —
foreach ( $array as $key => $value )
$ $key = $value ;
>
?>
This however would be reinventing the wheel when you can simply use:
extract ( $array , EXTR_OVERWRITE );
?>
Note that this will overwrite the contents of variables that already exist.
Extract has useful functionality to prevent this, or you may group the variables by using prefixes too, so you could use: —
$array =array( «one» => «First Value» ,
«two» => «2nd Value» ,
«three» => «8»
);
extract ( $array , EXTR_PREFIX_ALL , «my_prefix_» );
?>
This would create variables: —
$my_prefix_one
$my_prefix_two
$my_prefix_three
containing: —
«First Value», «2nd Value» and «8» respectively
21 years ago
Another use for this feature in PHP is dynamic parsing..
Due to the rather odd structure of an input string I am currently parsing, I must have a reference for each particular object instantiation in the order which they were created. In addition, because of the syntax of the input string, elements of the previous object creation are required for the current one.
Normally, you won’t need something this convolute. In this example, I needed to load an array with dynamically named objects — (yes, this has some basic Object Oriented programming, please bare with me..)
// this is only a skeletal example, of course.
$object_array = array();
// assume the $input array has tokens for parsing.
foreach ( $input_array as $key => $value ) <
// test to ensure the $value is what we need.
$obj = «obj» . $key ;
$ $obj = new Obj ( $value , $other_var );
Array_Push ( $object_array , $ $obj );
// etc..
>
?>
Now, we can use basic array manipulation to get these objects out in the particular order we need, and the objects no longer are dependant on the previous ones.
I haven’t fully tested the implimentation of the objects. The scope of a variable-variable’s object attributes (get all that?) is a little tough to crack. Regardless, this is another example of the manner in which the var-vars can be used with precision where tedious, extra hard-coding is the only alternative.
Then, we can easily pull everything back out again using a basic array function: foreach.
//.
foreach( $array as $key => $object )
echo $key . » — » . $object -> print_fcn (). »
\n» ;
?>
Through this, we can pull a dynamically named object out of the array it was stored in without actually knowing its name.