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

search for in the

Operators> <Constanten
Last updated: Wed, 22 Jul 2009

view this page in

Expressies

Expressies zijn de belangrijkste bouwstenen van PHP. In PHP is bijna alles wat je schrijft een expressie. De eenvoudigste en meest accurate manier om een expressie te defineren is "alles dat een waarde heeft".

De basisvorm van expressies zijn constanten en variabelen. Als je typt "$a = 5", dan geef je $a de waarde '5'. '5', heeft als waarde (natuulijk) 5, of met andere woorden '5' is een expressie met de waarde 5 (in dit voorbeeld, '5' is een integer constante).

Na deze toekenning verwacht je dat de waarde van $a ook 5 zal zijn, en als je nu zou schrijven $b = $a, dan verwacht je dat dit precies hetzelfde zal doen als $b = 5. Met andere woorden, $a is ook een expressie met de waarde 5. Als alles werkt zoals het hoort, zal $b dus ook de waarde 5 krijgen.

Wat complexere voorbeelden van expressies zijn functies. Kijk bijvoorbeeld naar de volgende functie:

function foo () {
    return 5;
}
     

Aangenomen dat je bekend met met het concept 'functies' (als je dit niet bent kijk dan in het hoofdstuk over functies), verwacht je dat het typen van $c = foo() in essentie precies hetzelfde is als het typen van $c = 5, en dit is ook waar. Functies zijn expressies met de waarde die gelijk is aan de return waarde van de functie. Omdat foo() 5 teruggeeft, is de waarde van de expressie 'foo()' 5. Normaal gesproken retourneren functies geen statische waarden natuurlijk, maar berekenen ze iets.

Natuurlijk kunnen waarden in PHP ook iets anders zijn dan integers. PHP ondersteunt drie scalaire types: integers, floating points en strings. (Scalaire types hebben waardes die je niet in kleinere stukken kunt breken, dit in tegenstelling tot bijvoorbeeld array's). PHP ondersteunt ook twee niet scalaire types: array's en objecten Al deze types kunnen worden toegekend aan variabelen of worden teruggegeven uit functies.

Tot zover zullen de gebruikers van PHP/FI 2 geen verschil merken, maar PHP gaat veel verder met expressies, op dezelfde manier als veel andere talen doen. PHP is een expressie-georiënteerde taal waarbij bijna alles een expressie is. Neem bijvoorbeeld het voorbeeld dat je eerder hebt gezien: '$a = 5'. Het is eenvoudig te zien dat het hier om twee waardes gaat, de waarde van de integer constante '5' en de waarde van $a waaraan 5 wordt toegekend. Maar in werkelijkheid is er nog een waarde, en deze waarde is de waarde van de toekenning zelf. De toekenning zelf evalueert tot de toegekende waarde, in dit geval 5. Dit betekent dat '$a = 5', terzijde gelegd wat het doet, een expressies is met de waarde 5. Dus als je zou schrijven: '$b = ($a = 5)' gebeurt er precies als je zou schrijven: '$a = 5; $b = 5;' (een puntkomma markeert het einde van een statement). Omdat toekenningen worden geparsed van rechts naar links, zou je ook kunnen schrijven '$b = $a = 5'.

Een ander goed voorbeeld van expressie oriëntatie zijn pre- en post-increment en decrement. Gebruikers van PHP/FI 2 en vele andere talen zullen wellicht de notatie variabele++ en variable-- kennen. Dit zijn de increment en decrement operaties. In PHP/FI 2, heeft het statement '$a++' geen waarde (het is geen expressie), en daarom kun je het niet toewijzen of gebruiken op een andere manier. PHP voegt increment/decrement toe aan de expressies, net zoals dit in C is. In PHP zijn er twee types increment, pre-increment en post-increment. Zowel pre-increment en post-increment verhogen de variabele, en het effect op de variabele is identiek. Het verschil ligt hem in de waarde van de totale increment expressie. Pre-increment, dat wordt geschreven als '++$variable', evalueert tot de opgehoogde waarde (PHP verhoogt de variabele voordat de waarde wordt gelezen, vandaar de naam 'pre-increment'). Post-increment, dat wordt geschreven als '$variable++' evalueert tot de oorspronkelijke waarde van $variable, voordat deze is opgehoogd (PHP verhoogt de variable nadat deze is uitgelezen, vandaar de naam 'post-increment').

Andere normale expressies zijn vergelijkingsexpressies. Deze expressies evalueren tot 0 of 1 (dit betekent respectievelijk FALSE en TRUE). PHP ondersteunt > (groter dan), >= (groter dan of gelijk aan), == (gelijk), != (niet gelijk), < (kleiner dan) en <= (kleiner dan of gelijk aan). Deze expressies worden meestal gebruikt binnen conditionele statements, zoals if statements.

Het laatste type expressies waar we het over zullen hebben zijn gecombineerde operatie-toewijzingsexpressies. Je weet al dat als je $a wilt verhogen met 1, je '$a++' of '++$a' kunt schrijven. Maar wat als je er meer bij wilt optellen, bijvoorbeeld 3? Je zou natuurlijk vaker '$a++' kunnen schrijven, maar dit is natuurlijk niet efficiënt of handig. Veel vaker wordt er geschreven '$a = $a + 3'. '$a + 3' evalueert tot de waarde van $a plus 3, en wordt dan weer teruggewezen aan $a, dit resulteert in een nieuwe waarde van $a die 3 onder de huidige waarde ligt. In PHP, en in vele andere talen waaronder C, kun je dit korter schrijven, zodat het makkelijker leest en sneller te begrijpen is. Het ophogen van de huidige waarde van $a met 3 kan worden geschreven als '$a += 3'. Dit betekent "neem de waarde van $a, tel er 3 bij op, en ken het weer toe aan $a". Als derde voordeel (naast korter en makkelijker te lezen, zal het statement ook sneller worden uitgevoerd. De waarde van '$a += 3', is net zoals de waarde van een normale toekenning, de toegekende waarde. Begrijp goed dat dit NIET 3 is, maar de gecombineerde waarde van $a plus 3 (dit is namelijk de waarde die wordt toegekend aan $a). Elke binaire operator kan worden gebruikt voor deze operatie-toekennings mode, bijvoorbeeld '$a -= 5' (verminder de waarde van $a met 5), '$b *= 7' (vermenigvuldig de waarde van $b met 7), enz.

Er is nog een expressie die vreemd zal lijken als je het nog niet hebt gezien in andere talen, namelijk de ternaire conditionele operator:

$eerste ? $tweede : $derde
Als de waarde van de eerste sub-expressie waar is (niet-nul), dan wordt de tweede sub-expressie geëvalueerd, en dit zal het resultaat zijn van de conditionele expressie. Anders wordt de derde sub-expressie geëvalueerd, en wordt dit de waarde van de operatie.

Het volgende voorbeeld helpt je met het beter begrijpen van pre- en post-increment en expressies in het algemeen:

<?php
function dubbel($i) {
    return $i*2;
}
$b = $a = 5;        /* ken de waarde 5 toe aan de variabelen $a en $b */
$c = $a++;          /* post-increment, ken de originele waarde van $a 
                       (5) toe aan $c */
$e = $d = ++$b;     /* pre-increment, ken de opgehoogde waarde van 
                       $b (6) toe aan $d en $e */

/* op dit punt zijn $d en $e beide gelijk aan 6 */

$f = double($d++);  /* ken twee keer de waarde van $d <emphasis>voor</emphasis> 
                       de ophoging, 2*6 = 12 toe aan $f */
$g = double(++$e);  /* ken twee keer de waarde van $e <emphasis>na</emphasis>
                       de ophoging, 2*7 = 14 toe aan $g */
$h = $g += 10;      /* als eerste wordt $g opgehoogd met 10 en eindigt met de 
                       waarde 24. De waarde van de toekenning (24) wordt dan
                       toegekend aan $h, zodat ook $h uiteindelijk de waarde
                       24 krijgt. */

Aan het begin van dit hoofdstuk vertelden we dat we verschillende statement types zouden beschrijven, en zoals is gebleken kunnen expressies statements zijn. Maar niet iederen expressie is een statement. Een statement heeft de vorm 'expressie' ';' dat is een expressie gevolgd door een punt-komma. In '$b=$a=5;' is $a=5 een geldige expressie, maar niet een statement. '$b=$a=5;' is wel een geldig statement in dit voorbeeld.

Er is nog een laatste ding waar we het over willen hebben, en dat is de waarheids-waarde van expressies. In veel gevallen, vaak in loops en andere conditionele dingen, ben je niet geïnteresseerd in een specifieke waarde, maar alleen of deze waarde TRUE of FALSE betekent. (PHP heeft geen apart boolean type). De waarheidswaarde van expressies in PHP is hetzelfde als dat in Perl. Alleen numerieke niet-nul waarden zijn TRUE, 0 is FALSE. Let er op dat negatieve waardes ook niet-nul zijn en daarom de waarheids-waarde TRUE is!. De lege string en de string "0" zijn ook FALSE; alle andere strings zijn TRUE. In het geval van niet scalaire waarden (array's en objecten) is de waardheids- waarde FALSE als deze geen elementen bevat, anders evalueren ze tot TRUE.

PHP heeft een volledige en krachtige implementatie van expressie, en om dit te documenteren gaat geheel buiten de scope van deze handleiding. De bovenstaande voorbeelden zouden je een goed idee moeten geen over wat expressies zijn en hoe je ze goed kan construeren. In de rest van deze handleiding zullen we expr schrijven om een geldige PHP expressie aan te geven.



Operators> <Constanten
Last updated: Wed, 22 Jul 2009
 
add a note add a note User Contributed Notes
Expressies
Magnus Deininger, dma05 at web dot de
16-Apr-2009 05:04
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.
phpsourcecode at blogspot dot com
02-Jul-2008 03:37
The ternary conditional operator is a useful way of avoiding
http://phpsourcecode.blogspot.com

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' ) ;
denzoo at gmail dot com
16-Mar-2008 01:52
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().
jvm at jvmyers dot com
24-Feb-2008 09:20
<?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!
petruzanauticoyahoo?com!ar
20-Oct-2007 05:41
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.
winks716
23-Aug-2007 10:42
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~ :)
george dot langley at shaw dot ca
20-Jul-2007 08:01
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
egonfreeman at gmail dot com
04-Apr-2007 04:45
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)
shawnster
15-Feb-2007 01:56
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.
nabil_kadimi at hotmail dot com
30-Jan-2007 04:46
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
?>
richard at phase4 dot ie
19-Jan-2006 09:00
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.
Martin K
21-Oct-2005 03:28
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.
stochnagara at hotmail dot com
19-Aug-2005 02:06
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;
}
12345alex at gmx dot net
14-Aug-2005 04:00
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
sabinx at gmail dot com
26-Jun-2005 08:25
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.
31-May-2005 09:07
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.
tom at darlingpet dot com
04-Feb-2005 11:13
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.
stian at datanerd dot net
25-Feb-2003 11: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
oliver at hankeln-online dot de
07-Aug-2002 03:06
The short-circuiting IS a feature. It is also available in C, so I suppose the developers won´t 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
17-Jul-2002 08: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!).
Mattias at mail dot ee
25-May-2002 12: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.
yasuo_ohgaki at hotmail dot com
12-Mar-2001 08:14
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.
anthony at n dot o dot s dot p dot a dot m dot trams dot com
24-Nov-2000 08: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' ) ;

Operators> <Constanten
Last updated: Wed, 22 Jul 2009
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites