Operator Precedence in PHP

December 16, 2007

The precedence of an operator specifies how “tightly” it binds two expressions together. Lets play with few of them

  1. ‘[' is left associative and has higher precedence than assignment operator '='
    function one($str)
    {
    echo "$str";
    return 1;
    }
    $a = array(1,2);
    $a[one("A")] = $a[one("B")] = 1; // outputs AB
  2. Assignment Operators are right associative
    function output(& $b)
    {
    echo( “b value is: “.$b );
    return $b;
    }
    $a = 2;
    $b = 5;
    echo ($a = $b = 1);
    $a = 2;
    $b = 5;
    echo ( “a value is: “.$a = output($b) );
    ?>
    Output is:
    1
    b value is: 5
    a value is: 5
  3. Comparison Operator always returns TRUE/FALSE
    $b = 5;
    $a = ( ( ++$b ) > 5 ); // Pre-increment test
    echo (int)$a; // Output 1
    $b = 5;
    $a = ( ( $b++ ) > 5 ); // Post-increment test
    echo (int)$a; // Output 0
  4. assignment operator has higher precedence than bitwise operator
    ( 9 & 8 == 8 ) ? ‘true’:'false’; //same as 9 & ( 8 == 8 ) which is true
    ( 8 & 8 == 8 ) ? ‘true’:'false’; //same as 8 & ( 8 == 8 ) which is false
  5. Logical Operator Precedence : and, or, nor, !, &&, ||
    $a && $b || $c; // equivalent to
    (a and b) or c
    $a AND $b || $c; // equivalent to a and (b or c)
    again
    $a = $b && $c; // equivalent to $a = (
    $b && $c)
    $a = $b AND $c; //
    equivalent to ($a = $b) && $c
  6. The ternary operator is a statement, and that it doesn’t evaluate to a variable, but to the result of a statement
    echo (true?’true’:false?’t':’f'); // equivalent to echo ((true ? ‘true’ : ‘false’) ? ‘t’ : ‘f’);

Reference : PHP Manual

Entry Filed under: ZEND PHP5 Exam. Tags: , , , .

1 Comment Add your own

  • 1. SPIGNEEUNINTY  |  August 3, 2008 at 1:08 pm

    It’s amazing

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Me in Brief

Expert Rating Certified Professional PHP5
Hi I am Shaikhul Islam Chowdhury Shaymol,
Currently working at Internet BS Corp as a Software Engineer.
I like to explore LAMP and other Web Technologies.
 

My LinkedIn Profile

View Shaikhul Islam Chowdhury Shaymol's profile on LinkedIn
 

Pages

Categories

Links

RSS PHP Magazine

RSS PHPGeek

Archives

Photos from FlickR

graduate

RoomMates@RashidHall.KUET

faruk monir monil n me

yamin me n tani apu

me@home

More Photos