PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<Predefined constantsOperators>
view the version of this page
Last updated: Thu, 21 Aug 2003

Chapter 9. Expressions

Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".

The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).

After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.

Slightly more complex examples for expressions are functions. For instance, consider the following function:

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

Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something.

Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports three scalar value types: integer values, floating point values and string values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.

So far, users of PHP/FI 2 shouldn't feel any change. However, PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5. Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'.

Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP/FI 2 and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP/FI 2, the statement '$a++' has no value (is not an expression), and thus you can't assign it or use it in any way. PHP enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is idential. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').

A very common type of expressions are comparison expressions. These expressions evaluate to either 0 or 1, meaning FALSE or TRUE (respectively). PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). These expressions are most commonly used inside conditional execution, such as if statements.

The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.

There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:

<?php
$first ? $second : $third
?>

If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.

The following example should help you understand pre- and post-increment and expressions in general a bit better:

<?php
function double($i)
{
    return $i*2;
}
$b = $a = 5;        /* assign the value five into the variable $a and $b */
$c = $a++;          /* post-increment, assign original value of $a 
                       (5) to $c */
$e = $d = ++$b;     /* pre-increment, assign the incremented value of 
                       $b (6) to $d and $e */

/* at this point, both $d and $e are equal to 6 */

$f = double($d++);  /* assign twice the value of $d before
                       the increment, 2*6 = 12 to $f */
$g = double(++$e);  /* assign twice the value of $e after
                       the increment, 2*7 = 14 to $g */
$h = $g += 10;      /* first, $g is incremented by 10 and ends with the 
                       value of 24. the value of the assignment (24) is 
                       then assigned into $h, and $h ends with the value 
                       of 24 as well. */
?>

In the beginning of the chapter we said that we'll be describing the various statement types, and as promised, expressions can be statements. However, not every expression is a statement. In this case, a statement has the form of 'expr' ';' that is, an expression followed by a semicolon. In '$b=$a=5;', $a=5 is a valid expression, but it's not a statement by itself. '$b=$a=5;' however is a valid statement.

One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE. The constants TRUE and FALSE (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the section about type-casting for details about how.

PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.



add a note add a note User Contributed Notes
Expressions
sea at zzti dot edu dot cn
09-Jun-2003 09:05
notice:

<?
$i
=2;
function 
double($i)
{
   return 
$i*2;
}
$j=double($i+1);
echo 
$j;          //output:6
?>

whereas,
<?
$i
=2;
function 
double($i)
{
   return 
$i*2;
}
$j=double($i++);
echo 
$j;          //output:4
?>
cmartin at orlando dot fl
21-Apr-2003 01:34
Got into trouble here when not enclosing my multiple expressions in parenthesis:

   if ($res = mysql_query($query) && $row = mysql_fetch_assoc($res))
   {
       echo "Got DB Row!: ";
       print_r($row);
   }

Results in a PHP warning:

   PHP Warning:  mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in test.php on line 10

   Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in test.php on line 10

By adding parenthesis around the assignment expressions...

   if (($res = mysql_query($query)) && ($row = mysql_fetch_assoc($res))) {
       echo "Got DB Row!: ";
       print_r($row);
   }

...results in the desired output:

   Got DB Row!: Array
   (
       [id] => 0
       [name] => "Foo!"
   )

A closer look at what happens when the right value of an assignment is false (when used as a test expression):

   $a = 0;

   if ($b = $a && $c = $b) {
       echo "Test true: ";
   }
   echo "a:$a b:$b c:$c";

...yields $b and $c as unset:

   a:0 b: c:

...while parenthesis modify $b's result:

   $a = 0;

   if (($b = $a) && ($c = $b)) {
       echo "Test true: ";
   }
   echo "a:$a b:$b c:$c";

...as $b being set and $c remaining unset (desired):

   a:0 b:0 c:

One may want to always enclose their singular expressions within parenthesis to avoid this feature/problem. :)
Miki
20-Apr-2003 08:24
It appears to me that % is simply the same as % in C++ which is the modulus operator.

modulus  - Returns the remainder obtained by dividing the first argument by the second argument.

So in the example above it's not subtracting 2 from it and returning the result, it's dividing $a by 2 and returning the remainder.
Ruben Bonke
09-Apr-2003 06:03
In case you want to check whether an INT is even or uneven, you could use the % operator. In the example below it has been put into an if-statement.

<?php
 
 
//Sets the variable a
 
$a=2;

 
//Start checking
 
if (($a%2)==0) {
   print 
"This is an even number";     //TRUE
} else {
   print 
"This is an uneven number"//FALSE


?>

How does it work?
$a%2: constantly substract 2 from int a.
if put in an if-statement like above, it keeps on substracting 2 from int a, until value is exactly 0 or lower than 2 and higher than 0.

Another example.

<?php
 
  $a
=9;
 
$b=8;
 
$c=7;

 
$outcome_A $a 3;
 
$outcome_B $b 3;
 
$outcome_C $c 3;

  print 
$outcome_A// result: 0
 
print $outcome_B// result: 2
 
print $outcome_C// result: 1

?>

I find this function useful for webdesign purposes.
For instance to colour the background of every even entry of database output.
stian at datanerd dot net
25-Feb-2003 06:37
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
rainerd at eldwood dot com
24-Dec-2002 04:01
"Any two-place operator can be used in this operator-assignment mode."

It should be mentioned that this does not apply to the comparison operators.  $a <= $b is obviously not the same as $a = $a < $b.
oliver at hankeln-online dot de
07-Aug-2002 08:06
The short-circuiting IS a feature. It is also available in C, so I suppose the developers wonæ„’ remove it in future PHP versions.

It is rather nice to write:

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

Greets,
Oliver
php at cotest dot com
18-Jul-2002 01:08
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!).
iamfast at tampabay dot rr dot com
17-Jul-2002 03:47
If you need to do something like make sure you dont say '1 days' try this

echo $being-$today.' day'.($begin-$today===1?'':'s').' untill XYZ';
toreilly at cityspree dot com
28-May-2002 04:30
I actually find the short-circuit aspect of expressions useful.  As in:
if ($foo AND Bar()) { echo "OK"; }

where Bar() should only be run if $foo is set, and OK should only be printed if both evaluate to TRUE.

My only concern is if this is the intended result in PHP.  In other words, if I code this way will it fail under later releases of PHP?
Mattias at mail dot ee
25-May-2002 05:29
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.
09-Mar-2002 05:20
I found this worked nicely:

echo $var ? "yup" : "nope";

This doesnt work:

echo $var ? "yup";

you need to go:

echo $var ? "yup" : "";

-- there is not space in "", but it may appear that way above
tmacamNOSP at Mufc dot br
13-Sep-2001 01:57
As reported previously, PHP boolean operators seem to short-circuit. What if you want them to do not short-circuit?

Exemple:
$result_of = f1() and f2() and f3()

suppose you want to run f3 even when f1 already returned false.

If you perform some silly tests such as:
echo true + true;
you'll see that indeed, true=1 and false=0 and true+true = 2 (ok. this _is_ silly!)

Anyway, the point is: you could use * (multiplication) instead of 'and', to get a not short-circuiting 'and' and + (sum) to get a not short-circuiting or.


[]s
MaCa
yasuo_ohgaki at hotmail dot com
12-Mar-2001 03:14
Manual defines "expression is anything that has value", Therefore, parser will give error for following code.

($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,

($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.
mircho at _NO_SPAM_abv dot bg
24-Jan-2001 04:23
try this

$a = "-1";
$a++;
echo $a;

this prints -2 as a result

to be sure you get what you wanted to get just do this

$a = "-2"
$b = (integer)($a)
and now $b will behave

somebody mentioning strict typing?
anthony at n dot o dot s dot p dot a dot m dot trams dot com
25-Nov-2000 03:01
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' ) ;

<Predefined constantsOperators>
 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: http://php.mirrors.ilisys.com.au/
Last updated: Sat 01 Nov 2003 04:13:36 EST EST