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

search for in the

代数演算子> <
[edit] Last updated: Mon, 01 Nov 2010

view this page in

第 15章演算子

演算子とは、ひとつ以上の値 (あるいはプログラミング用語における「式」) から別の値 (制御構造が式になるように) を生み出すものです。 つまり、値を返す関数や制御構造 (たとえば print) は演算子と考えられますし、 何も値を返さないもの (たとえば echo) はそれ以外のものとなります。

演算子には 3 種類あります。ひとつめは単項演算子で、これはひとつの値に 対してのみ作用します。例えば ! (否定演算子) や ++ (加算子) などです。 ふたつめは二項演算子と呼ばれるものです。PHP がサポートしている演算子の ほとんどはここに含まれ、その一覧は 演算子の優先順位 にあります。

最後のグループは、三項演算子 ?: です。これは、2 つの文や実行経路から選択すると いうよりも、3 番目の式に応じて 2 つの式から選択するために使用されるべきです。 この演算子を使用する式は、括弧で囲んでおくことをお勧めします。

演算子の優先順位

演算子の優先順位は、二つの式が"緊密に"結合している度合いを指定します。 例えば、式 1 + 5 * 3 の答えは 16 になり、18 とはなりません。 これは乗算演算子("*")は、加算演算子("+")より高い優先順位を有するか らです。必要に応じて強制的に優先順位を設定するために括弧を使用する ことが可能です。例えば、18と評価するためには、 (1 + 5) * 3 とします。 演算子の優先順位が等しい場合は、左から右へ順に評価されます。

以下の表では、優先順位が高い順に演算子を挙げています。 同じ行にある演算子は優先順位が等しくなります。そのような場合は、 結合時の評価にしたがって評価順が決まります。

表 15-1. 演算子の優先順位

結合時の評価演算子追加情報
結合しないnewnew
left[array()
結合しない++ -- 加算子/減算子
結合しない~ - (int) (float) (string) (array) (object) @
結合しないinstanceof
right! 論理演算子
left* / % 代数演算子
left+ - . 代数演算子 そして 文字列演算子
left<< >> ビット演算子
結合しない< <= > >= 比較演算子
結合しない== != === !== 比較演算子
left& ビット演算子 そして リファレンス
left^ ビット演算子
left| ビット演算子
left&& 論理演算子
left|| 論理演算子
left? : 三項演算子
right = += -= *= /= .= %= &= |= ^= <<= >>= 代入演算子
leftand 論理演算子
leftxor 論理演算子
leftor 論理演算子
left,さまざまな利用法

結合時の評価が left の場合は式が左から右に評価され、一方 right の場合は その逆となります。

例 15-1. 結合時の評価

<?php
$a
= 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>
コードの可読性を高めるためには括弧を使用します。

注意: != よりも優先されるはずなのにもかかわらず、 PHP は依然として if (!$a = foo()) のような式も許します。この場合は foo() の返り値が $a に代入されます。



代数演算子> <
[edit] Last updated: Mon, 01 Nov 2010
 
add a note add a note User Contributed Notes 演算子
pgarvin76+php dot net at NOSPAMgmail dot com 29-Dec-2008 04:43
Method chaining is read left to right (left associative):
<?php

class Test_Method_Chain
{
    public function
One()
    {
        echo
"One" . PHP_EOL;
        return
$this;
    }

    public function
Two()
    {
        echo
"Two" . PHP_EOL;
        return
$this;
    }

    public function
Three()
    {
        echo
"Three" . PHP_EOL;
        return
$this;
    }
}

$test = new Test_Method_Chain();

$test->One()->Two()->Three();

/* Ouputs:
One
Two
Three
*/
?>
ddascalescu at gmail dot com 23-Oct-2008 06:53
The -> operator, not listed above, is called "object operator" (T_OBJECT_OPERATOR).
figroc at gmail dot com 02-Aug-2008 03:30
The variable symbol '$' should be considered as the highest-precedence operator, so that the variable variables such as $$a[0] won't confuse the parser.  [http://www.php.net/manual/en/language.variables.variable.php]
phpnet dot 20 dot dpnsubs at xoxy dot net 01-Nov-2007 02:13
Note that in php the ternary operator ?: has a left associativity unlike in C and C++ where it has right associativity.

You cannot write code like this (as you may have accustomed to in C/C++):
<?php
$a
= 2;
echo (
   
$a == 1 ? 'one' :
   
$a == 2 ? 'two' :
   
$a == 3 ? 'three' :
   
$a == 4 ? 'four' : 'other');
echo
"\n";
// prints 'four'
?>

You need to add brackets to get the results you want:
<?
$a
= 2;

echo (
$a == 1 ? 'one' :
        (
$a == 2 ? 'two' :
        (
$a == 3 ? 'three' :
        (
$a == 4 ? 'four' : 'other') ) ) );
echo
"\n";
//prints 'two'

?>
Gautam 10-Oct-2007 03:22
<?php

$result1
= 7 + 8 * 9/3 -4;
$result2 = 7 + 8 * (9/3 -4);
$result3 =(7 + 8)* 9/3 -4;

echo
"Result1 for 7 + 8 * 9/3 -4 = $result1  Result2 for 7 + 8 * (9/3 -4) = $result2 and Result3 (7 + 8)* 9/3 -4 = $result3 "
/*
 which gives results as under
 Result1 for 7 + 8 * 9/3 -4 = 27 Result2 for 7 + 8 * (9/3 -4) = -1 and Result3 (7 + 8)* 9/3 -4 = 41
 Execution Order is 1) expression in brackets 2) division 3) multiplication 4) addition and 5) subtraction
*/
?>
janturon at email dot cz 08-Oct-2007 06:42
This is very common problem: set one variable to another, if it is not empty. If it is, set it to something else.
For example: set $bar to $foo, if $foo is empty, set $bar to "undefined";

if(!empty($foo)) $bar= $foo; else $bar= "undefined";

OR operator can shorten it:

$bar= @$foo or $bar= "undefined";
me at robrosenbaum dot com 12-Jul-2007 12:16
The scope resolution operator ::, which is missing from the list above, has higher precedence than [], and lower precedence than 'new'. This means that self::$array[$var] works as expected.
madcoder at gmail dot com 09-Jun-2007 03:17
In response to mathiasrav at gmail dot com:

The reason for that behavior is the parentheses.  From the description:

"Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18."

So the order of operations says that even though the equality operator has higher precedence, the parentheses in your statement force the assignment operator to a higher precedence than the equality operator.

That said, it still doesn't work the way you expect it to.  Neither way works, for these reasons:
<?php
if ( $a != ($a = $b) )
?>

Order of operations says to do the parentheses first.  So you end up with:
<?php
$a
= $b;
if (
$a != $a )
?>

Which is obviously going to be false.  Without the parentheses:
<?php
if ( $a != $a = $b )
?>

Order of operations says to do the inequality first, then the assignment, so you have:
<?php
if ( $a != $a );
$a = $b;
?>

Which again is not what you expected, and again will always be false.  But because you are only working with values of 0 and 1, you can make use of the XOR operator:

<?php
if ( $a ^= $b )
?>

This will only be true if 1) $a is 0 and $b is 1, or 2) $a is 1 and $b is 0.  That is precisely what you wanted, and it even does the assignment the way you expected it to.

<?php
foreach ($ourstring as $c) {
  if (
$bold ^= $c['bold']) $resstring .= bold;
  if (
$underline ^= $c['underline']) $resstring .= underline;
 
$resstring .= $c[0];
}
?>

That code now works and produces the output you expected.
golotyuk at gmail dot com 09-Jul-2006 09:51
Simple POST and PRE incremnt sample:

<?php

$b
= 5;
$a = ( ( ++$b ) > 5 ); // Pre-increment test
echo (int)$a;

$b = 5;
$a = ( ( $b++ ) > 5 ); // Post-increment test
echo (int)$a;

?>

This will output 10, because of the difference in post- and pre-increment operations
rick at nomorespam dot fourfront dot ltd dot uk 02-Sep-2005 03:51
A quick note to any C developers out there, assignment expressions are not interpreted as you may expect - take the following code ;-

<?php
$a
=array(1,2,3);
$b=array(4,5,6);
$c=1;

$a[$c++]=$b[$c++];

print_r( $a ) ;
?>

This will output;-
Array ( [0] => 1 [1] => 6 [2] => 3 )
as if the code said;-
$a[1]=$b[2];

Under a C compiler the result is;-
Array ( [0] => 1 [1] => 5 [2] => 3 )
as if the code said;-
$a[1]=$b[1];

It would appear that in php the increment in the left side of the assignment is processed prior to processing the right side of the assignment, whereas in C, neither increment occurs until after the assignment.
09-Jun-2004 05:58
of course this should be clear, but i think it has to be mentioned espacially:

AND is not the same like &&

for example:

<?php $a && $b || $c; ?>
is not the same like
<?php $a AND $b || $c; ?>

the first thing is
(a and b) or c

the second
a and (b or c)

'cause || has got a higher priority than and, but less than &&

of course, using always [ && and || ] or [ AND and OR ] would be okay, but than you should at least respect the following:

<?php $a = $b && $c; ?>
<?php $a
= $b AND $c; ?>

the first code will set $a to the result of the comparison $b with $c, both have to be true, while the second code line will set $a like $b and THAN - after that - compare the success of this with the value of $c

maybe usefull for some tricky coding and helpfull to prevent bugs :D

greetz, Warhog
yasuo_ohgaki at hotmail dot com 25-Mar-2001 11:53
Other Language books' operator precedence section usually include "(" and ")" - with exception of a Perl book that I have. (In PHP "{" and "}" should also be considered also). However, PHP Manual is not listed "(" and ")" in precedence list. It looks like "(" and ")" has higher precedence as it should be.

Note: If you write following code, you would need "()" to get expected value.

<?php
$bar
= true;
$str = "TEST". ($bar ? 'true' : 'false') ."TEST";
?>

Without "(" and ")" you will get only "true" in $str.
(PHP4.0.4pl1/Apache DSO/Linux, PHP4.0.5RC1/Apache DSO/W2K Server)
It's due to precedence, probably.

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