downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

Операторы> <"Волшебные" константы
[edit] Last updated: Fri, 26 Apr 2013

view this page in

Выражения

Выражения - это самые важные строительные элементы PHP. Почти все, что вы пишете в PHP, является выражением. Самое простое и точное определение выражения - "все что угодно, имеющее значение".

Основными формами выражений являются константы и переменные. Если вы записываете "$a = 5", вы присваиваете '5' переменной $a. '5', очевидно, имеет значение 5 или, другими словами, '5' это выражение со значением 5 (в данном случае '5' - это целочисленная константа).

После этого присвоения вы ожидаете, что значением $a также является 5, поэтому, если вы написали $b = $a, вы полагаете, что работать это будет так же, как если бы вы написали $b = 5. Другими словами, $a это также выражение со значением 5. Если все работает верно, то именно так и произойдет.

Немного более сложными примерами выражений являются функции. Например, рассмотрим следующую функцию:

<?php
function foo ()
{
    return 
5;
}
?>

Исходя из того, что вы хорошо знакомы с концепцией функций (если нет, то прочитайте главу о функциях), вы полагаете, что запись $c = foo() абсолютно эквивалентна записи $c = 5, и вы правы. Функции - это выражения, значением которых является то, что возвращает функция. Поскольку foo() возвращает 5, значением выражения 'foo()' является 5. Как правило, функции возвращают не просто статическое значение, а что-то вычисляют.

Разумеется, значения в PHP не обязаны быть целочисленными, и очень часто ими не являются. PHP поддерживает четыре типа скалярных значений: целочисленные (integer), с плавающей точкой (float), строковые значения (string) и булевы (boolean) значения (скалярными являются значения, которые вы не можете 'разбить' на меньшие части, в отличие, например, от массивов). PHP поддерживает также два комбинированных (не скалярных) типа: массивы и объекты. Любое значение такого типа может присваиваться переменной или возвращаться. функцией.

Однако PHP, как и многие другие языки, понимает гораздо больше выражений. PHP - это язык, ориентированный на выражения и рассматривающий почти все как выражение. Вернемся к примеру, с которым мы уже имели дело: '$a = 5'. Легко заметить, что здесь присутствуют два значения - значение целочисленной константы '5' и значение переменной $a, также принимающей значение 5. Но на самом деле здесь присутствует и еще одно значение - значение самого присвоения. Само присвоение вычисляется в присвоенное значение, в данном случае - в 5. На практике это означает, что '$a = 5', независимо от того, что оно делает, является выражением со значением 5. Таким образом, запись '$b = ($a = 5)' равносильна записи '$a = 5; $b = 5;' (точка с запятой обозначает конец выражения). Поскольку операции присвоения анализируются справа налево, вы также можете написать '$b = $a = 5'.

Другой хороший пример ориентированности на выражения - префиксный и постфиксный инкремент и декремент. Пользователи PHP и многих других языков возможно уже знакомы с формой записи variable++ и variable--. Это операторы инкремента и декремента. Также как и C, PHP поддерживает два типа инкремента - префиксный и постфиксный. Они оба инкрементируют значение переменной и эффект их действия на нее одинаков. Разница состоит в значении выражения инкремента. Префиксный инкремент, записываемый как '++$variable', вычисляется в инкрементированное значение (PHP инкрементирует переменную до того как прочесть ее значение, отсюда название 'пре-инкремент'). Постфиксный инкремент, записываемый как '$variable++', вычисляется в первоначальное значение переменной $variable до ее приращения (PHP инкрементирует переменную после прочтения ее значения, отсюда название 'пост-инкремент').

Очень распространенным типом выражений являются выражения сравнения. Результатом вычислений являются FALSE (ложь) или TRUE (истина). PHP поддерживает операции сравнения > (больше), >= (больше либо равно), == (равно), != (не равно), < (меньше) и <= (меньше либо равно). Он также поддерживает операторы строгого равенства: === (равно и одного типа) и !== (не равно или не одного типа). Чаще всего эти выражения используются в операторах условного выполнения, таких как if.

Последний пример выражений, который мы здесь рассмотрим, это смешанные выражения операции и присвоения. Вы уже знаете, что если вы хотите увеличить $a на 1, вы можете просто написать '$a++' или '++$a'. Но что, если вы хотите прибавить больше, чем единицу,например, 3? Вы могли бы написать '$a++' много раз, однако, очевидно это не очень рациональный и удобный способ. Гораздо более распространенной практикой является запись вида '$a = $a + 3'. '$a + 3' вычисляется в значение $a плюс 3 и снова присваивается $a, увеличивая в результате $a на 3. В PHP, как и в некоторых других языках, таких как C, вы можете записать это более коротким образом, что увеличит очевидность смысла и быстроту понимания кода по прошествии времени. Прибавить 3 к текущему значению $a можно с помощью записи '$a += 3'. Это означает дословно "взять значение $a, прибавить к нему 3 и снова присвоить его переменной $a". Кроме большей понятности и краткости, это быстрее работает. Значением '$a += 3', как и обычного присвоения, является присвоенное значение. Обратите внимание, что это НЕ 3, а суммированное значение $a плюс 3 (то, что было присвоено $a). Таким образом может использоваться любой бинарный оператор, например, '$a -= 5' (вычесть 5 из значения $a), '$b *= 7' (умножить значение $b на 7) и т.д.

Существует еще одно выражение, которое может выглядеть необычно, если вы не встречали его в других языках - тернарный условный оператор:

<?php
$first 
$second $third
?>

Если значением первого подвыражения является TRUE (не ноль), то выполняется второе подвыражение, которое и будет результатом условного выражения. В противном случае будет выполнено третье подвыражение и его значение будет результатом.

Следующий пример должен помочь вам немного улучшить понимание префиксного и постфиксного инкремента и выражений:

<?php
function double($i)
{
    return 
$i*2;
}
$b $a 5;        /* присвоить значение пять переменным $a и $b */
$c $a++;          /* постфиксный инкремент, присвоить значение $a 
                       (5) переменной $c */
$e $d = ++$b;     /* префиксный инкремент, присвоить увеличенное
                       значение $b (6) переменным $d и $e */

/* в этой точке и $d, и $e равны 6 */

$f double($d++);  /* присвоить удвоенное значение $d перед
                       инкрементом (2*6 = 12) переменной $f */
$g double(++$e);  /* присвоить удвоенное значение $e после
                       инкремента (2*7 = 14) переменной $g */
$h $g += 10;      /* сначала переменная $g увеличивается на 10,
                       приобретая, в итоге, значение 24. Затем значение
                       присвоения (24) присваивается переменной $h,
                       которая в итоге также становится равной 24. */
?>

Некоторые выражения могут рассматриваться как инструкции. В данном случае инструкция имеет вид 'expr ; - выражение с последующей точкой с запятой. В записи '$b = $a = 5;', $a = 5 - это верное выражение, но само по себе не инструкция. Тогда как '$b = $a = 5;' является верной инструкцией.

Последнее, что стоит упомянуть, это истинность значения выражений. Во многих случаях, как правило, в условных операторах и циклах, вас может интересовать не конкретное значение выражения, а только его истинность (значение TRUE или FALSE). Константы TRUE и FALSE (регистро-независимые) - это два возможных булевых значения. При необходимости выражение автоматически преобразуется в булев тип. Подробнее о том, как это происходит, смотрите в разделе о приведении типов.

PHP предоставляет полную и мощную реализацию выражений, и их полное документирование выходит за рамки этого руководства. Вышеприведенные примеры должны дать вам представление о том, что они из себя представляют и как вы сами можете создавать полезные выражения. Далее, для обозначения любого верного выражения PHP в этой документации мы будем использовать сокращение expr.



add a note add a note User Contributed Notes Выражения - [24 notes]
up
9
Magnus Deininger, dma05 at web dot de
4 years ago
Note that even though PHP borrows large portions of its syntax from C, the ',' is treated quite differently. It's not possible to create combined expressions in PHP using the comma-operator that C has, except in for() loops.

Example (parse error):

<?php

$a
= 2, $b = 4;

echo
$a."\n";
echo
$b."\n";

?>

Example (works):
<?php

for ($a = 2, $b = 4; $a < 3; $a++)
{
  echo
$a."\n";
  echo
$b."\n";
}

?>

This is because PHP doesn't actually have a proper comma-operator, it's only supported as syntactic sugar in for() loop headers. In C, it would have been perfectly legitimate to have this:

int f()
{
  int a, b;
  a = 2, b = 4;

  return a;
}

or even this:

int g()
{
  int a, b;
  a = (2, b = 4);

  return a;
}

In f(), a would have been set to 2, and b would have been set to 4.
In g(), (2, b = 4) would be a single expression which evaluates to 4, so both a and b would have been set to 4.
up
5
winks716
5 years ago
reply to egonfreeman at gmail dot com
04-Apr-2007 07:45

the second example u mentioned as follow:
=====================================

$n = 3;
$n * $n++

from 3 * 3 into 3 * 4. Post- operations operate on a variable after it has been 'checked', but it doesn't necessarily state that it should happen AFTER an evaluation is over (on the contrary, as a matter of fact).

===========================================

everything works correctly but one sentence should be modified:

"from 3 * 3 into 3 * 4"  should be "from 3 * 3 into 4 * 3"

best regards~ :)
up
3
Mattias at mail dot ee
10 years ago
A note about the short-circuit behaviour of the boolean operators.

1. if (func1() || func2())
Now, if func1() returns true, func2() isn't run, since the expression
will be true anyway.

2. if (func1() && func2())
Now, if func1() returns false, func2() isn't run, since the expression
will be false anyway.

The reason for this behaviour comes probably from the programming
language C, on which PHP seems to be based on. There the
short-circuiting can be a very useful tool. For example:

int * myarray = a_func_to_set_myarray(); // init the array
if (myarray != NULL && myarray[0] != 4321) // check
    myarray[0] = 1234;

Now, the pointer myarray is checked for being not null, then the
contents of the array is validated. This is important, because if
you try to access an array whose address is invalid, the program
will crash and die a horrible death. But thanks to the short
circuiting, if myarray == NULL then myarray[0] won't be accessed,
and the program will work fine.
up
3
anthony at n dot o dot s dot p dot a dot m dot trams dot com
12 years ago
The ternary conditional operator is a useful way of avoiding inconvenient if statements.  They can even be used in the middle of a string concatenation, if you use parentheses. 

Example:

if ( $wakka ) {
  $string = 'foo' ;
} else {
  $string = 'bar' ;
}

The above can be expressed like the following:

$string = $wakka ? 'foo' : 'bar' ;

If $wakka is true, $string is assigned 'foo', and if it's false, $string is assigned 'bar'.

To do the same in a concatenation, try:

$string = $otherString . ( $wakka ? 'foo' : 'bar' ) ;
up
1
jvm at jvmyers dot com
5 years ago
<?php
// Compound booleans expressed as string args in an 'if' statement don't work as expected:
//
//    Context:
//        1.  I generate an array of counters
//        2.  I dynamically generate a compound boolean based on selected counters in the array
//                Note: since the real array is sparse, I must use the 'empty' operator
//        3.  When I submit the compound boolean as the expression of an 'if' statement,
//            the 'if' appears to resolve ONLY the first element of the compound boolean.
//    Conclusion: appears to be a short-circuiting issue

$aArray = array(1,0);

// Case 1: 'if' expression passed as string:

$sCondition = "!empty($aArray[0]) && !empty($aArray[1])";
if (
$sCondition)
{
    echo
"1. Conditions met<br />";
}
else
{
    echo
"1. Conditions not met<br />";
}

// Case 1 output:  "1. Conditions met"

// Case 2: same as Case 1, but using catenation operator

if ("".$sCondition."")
{
    echo
"2. Conditions met<br />";
}
else
{
    echo
"2. Conditions not met<br />";
}

// Case 2 output:  "2. Conditions met"

// Case 3: same 'if' expression but passed in context:

if (!empty($aArray[0]) && !empty($aArray[1]))
{
    echo
"3. Conditions met<br />";
}
else
{
    echo
"3. Conditions not met<br />";
}

// Case 3 output:  "3. Conditions not met"

// jvm@jvmyers.com
?>

PS: the bug folks say this "does not imply a bug in PHP itself."  Sure bugs me!
up
1
shawnster
6 years ago
An easy fix (although intuitively tough to do...) is to reverse the comparison.

if (5 == $a) {}

If you forget the second '=', you'll get a parse error for trying to assign a value to a non-variable.
up
0
antickon at gmail dot com
1 year ago
evaluation order of subexpressions is not strictly defined for all operators

<?php
function a() {echo 'a';}
function
b() {echo 'b';}
a() == b(); // outputs "ab", ie evaluates left-to-right

$a = 3;
var_dump( $a == $a = 4 ); // outputs bool(true), ie evaluates right-to-left
?>

this is not a bug: "we [php developers] make no guarantee about the order of evaluation".
See https://bugs.php.net/bug.php?id=61188
up
0
george dot langley at shaw dot ca
5 years ago
Here's a quick example of Pre and Post-incrementation, in case anyone does feel confused (ref anonymous poster 31 May 2005)

<?PHP
echo "Using Pre-increment ++\$a:<br>";
$a = 1;
echo
"\$a = $a<br>";
$b = ++$a;
echo
"\$b = ++\$a, so \$b = $b and \$a = $a<br>";
echo
"<br>";
echo
"Using Post-increment \$a++:<br>";
$a = 1;
echo
"\$a = $a<br>";
$b = $a++;
echo
"\$b = \$a++, so \$b = $b and \$a = $a<br>";
?>

HTH
up
0
nabil_kadimi at hotmail dot com
6 years ago
Attention! php will not warn you if you write (1) When you mean (2)

(1)
<?
if($a=0)
    echo "condition is true";
else
    echo "condition is false";
//output: condition is false
?>

(2)
<?
if($a==0)
    echo "condition is true";
else
    echo "condition is false";
//output: condition is true
?>
up
0
tom at darlingpet dot com
8 years ago
Something I've noticed with ternary expressions is if you do something like :

<?= $var=="something" ? "is something" : "not something"; ?>

It will give wacky results sometimes...

So be sure to enclose the ternary expression in parenthesis when ever necessary (such as having multiple expressions or nested ternary expressions)

The above could look like:

<?= ($var=="something") ? "is something" : "not something"; ?>

It's also a good idea to use parenthesis when using something SIMILAR to:

<?php
echo (trim($var)=="") ? "empty" : "not empty";
?>

In some cases other than the <?= ?> example, not placing the entire expression in appropriate parenthesis might yield undesirable results as well.. but I'm not quite sure.
up
0
oliver at hankeln-online dot de
10 years ago
The short-circuiting IS a feature. It is also available in C, so I suppose the developers wont remove it in future PHP versions.

It is rather nice to write:

$file=fopen("foo","r") or die("Error!");

Greets,
Oliver
up
-1
Martin K
7 years ago
At 04-Feb-2005 05:13, tom at darlingpet dot com said:
> It's also a good idea to use parenthesis when using something SIMILAR to:
>
> <?php
> echo (trim($var)=="") ? "empty" : "not empty";
>
?>

No, it's a BAD idea.

All the short-circuiting operators, including the ternary conditional operator, have LOWER precedence than the comparison operators, so they almost NEVER need parentheses around their subexpressions.

Inserting the parentheses suggested above does not change the meaning of the code, but their use misleads inexperienced programmers to expect that things like this will work in a similar manner:

<?php
function my_print($a) { print($a); }
my_print (trim($var)=="") ? "empty" : "not empty";
?>

when of course it doesn't.

Rather than worrying that code doesn't work as expected, simply learn the precedence rules (http://www.php.net/manual/en/language.operators.php) so that one expects the right things.
up
-1
12345alex at gmx dot net
7 years ago
this code:
    print array() == NULL ? "True" : "False";
    print " (" . (array() == NULL) . ")\n";

    $arr = array();
    print array() == $arr ? "True" : "False";
    print " (" . (array() == $arr) . ")\n";

    print count(array()) . "\n";
    print count(NULL) . "\n";

will output (on php4 and php5):
    True (1)
    True (1)
    0
    0

so to decide wether i have NULL or an empty array i will also have to use gettype(). this seems some kind of weird for me, although if is this is a bug, somebody should have noticed it before.

alex
up
-2
egonfreeman at gmail dot com
6 years ago
It is worthy to mention that:

$n = 3;
$n * --$n

WILL RETURN 4 instead of 6.

It can be a hard to spot "error", because in our human thought process this really isn't an error at all! But you have to remember that PHP (as it is with many other high-level languages) evaluates its statements RIGHT-TO-LEFT, and therefore "--$n" comes BEFORE multiplying, so - in the end - it's really "2 * 2", not "3 * 2".

It is also worthy to mention that the same behavior will change:

$n = 3;
$n * $n++

from 3 * 3 into 3 * 4. Post- operations operate on a variable after it has been 'checked', but it doesn't necessarily state that it should happen AFTER an evaluation is over (on the contrary, as a matter of fact).

So, if you ever find yourself on a 'wild goose chase' for a bug in that "impossible-to-break, so-very-simple" piece of code that uses pre-/post-'s, remember this post. :)

(just thought I'd check it out - turns out I was right :P)
up
0
petruzanauticoyahoo?com!ar
5 years ago
Regarding the ternary operator, I would rather say that the best option is to enclose all the expression in parantheses, to avoid errors and improve clarity:

<?php
  
print ( $a > 1 ? "many" : "just one" );
?>

PS: for php, C++, and any other language that has it.
up
0
richard at phase4 dot ie
7 years ago
Follow up on Martin K. There are no hard and fast rules regarding operator precedence. Newbies should definitely learn them, but if their use results in code that is not easy to read you should use parentheses. The two important things are that it works properly AND is maintainable by you and others.
up
0
Anonymous
7 years ago
I don't see why it is necessary here to explain pre- and post- incrementing.

This is something that will confuse new users of PHP, even longer time programmers will sometimes miss a the fine details of a construct like that.

If something has a side-effect it should be on a line of it's own, or at least be an expression of it's own and not part of an assignment, condition or whatever.
up
0
php at cotest dot com
10 years ago
It should probably be mentioned that the short-circuiting of expressions (mentioned in some of the comments above) is often called "lazy evaluation" (in case someone else searches for the term "lazy" on this page and comes up empty!).
up
0
yasuo_ohgaki at hotmail dot com
12 years ago
Manual defines "expression is anything that has value", Therefore, parser will give error for following code.

<?php
($val) ? echo('true') : echo('false');
Note: "? : " operator has this syntax  "expr ? expr : expr;"
?>

since echo does not have(return) value and ?: expects expression(value).

However, if function/language constructs that have/return value, such as include(), parser compiles code.

Note: User defined functions always have/return value without explicit return statement (returns NULL if there is no return statement). Therefore, user defined functions are always valid expressions.
[It may be useful to have VOID as new type to prevent programmer to use function as RVALUE by mistake]

For example,

<?php
($val) ? include('true.inc') : include('false.inc');
?>

is valid, since "include" returns value.

The fact "echo" does not return value(="echo" is not a expression), is less obvious to me.

Print() and Echo() is NOT identical since print() has/returns value and can be a valid expression.
up
-1
denzoo at gmail dot com
5 years ago
To jvm at jvmyers dot com:
Your first two if statements just check if there's anything in the string, if you wish to actually execute the code in your string you need eval().
up
-1
stochnagara at hotmail dot com
7 years ago
12345alex at gmx dot net 's case is actually handled by the === operator. That's what he needs.

There is also another widely used function. I call it myself is_nil which is true for NULL,FALSE,array() and '', but not for 0 and "0".

function is_nil ($value) {
 return !$value && $value !== 0 && $value !== '0';
}

Another useful function is "get first argument if it is not empty or get second argument otherwise". The code is:

function def ($value, $defaultValue) {
 return is_nil ($value) ? $defaultValue : $value;
}
up
-2
sabinx at gmail dot com
7 years ago
Pre- and Post-Incrementation, I believe, are important to note and in the correct place. The section deals with the value of an expression. ++$a and $a++ have different values, and both forms have valid uses.

And, because it can be confusing, it is that much more important to note. Although it could be worded better, it does belong.
up
-2
stian at datanerd dot net
10 years ago
The short-circuit feature is indeed intended, and there are two types of evaluators, those who DO short-circuit, and those who DON'T, || / && and | / & respectively.
The latter method is the bitwise operators, but works great with the usual boolean values ( 0/1 )

So if you don't want short-circuiting, try using the | and & instead.

Read more about the bitwise operators here:
http://www.php.net/manual/en/language.operators.bitwise.php
up
-4
phpsourcecode at blogspot dot com
4 years ago
The ternary operator is a convenient way to conditionally return an expression.  They can even be used in the middle of a string concatenation, if you use parentheses.

Example:

if ( $wakka ) {
  $string = 'foo' ;
} else {
  $string = 'bar' ;
}

The above can be expressed like the following:

$string = $wakka ? 'foo' : 'bar' ;

If $wakka is true, $string is assigned 'foo', and if it's false, $string is assigned 'bar'.

To do the same in a concatenation, try:

$string = $otherString . ( $wakka ? 'foo' : 'bar' ) ;

 
show source | credits | stats | sitemap | contact | advertising | mirror sites