php數組運算子,字串運算子和邏輯運算子執行個體詳解

來源:互聯網
上載者:User
php數組運算子

$a + $b 聯合 $a 和 $b 的聯合。
$a == $b 相等 如果 $a 和 $b 具有相同的鍵/值對則為 TRUE。
$a === $b 全等 如果 $a 和 $b 具有相同的鍵/值對並且順序和類型都相同則為 TRUE。
$a != $b 不等 如果 $a 不等於 $b 則為 TRUE。
$a <> $b 不等 如果 $a 不等於 $b 則為 TRUE。
$a !== $b 不全等 如果 $a 不全等於 $b 則為 TRUE。

PHP 僅有的一個數組運算子是 + 運算子。它把右邊的數組附加到左邊的數組後,但是重複的索引值不會被覆蓋。

$a = array("a" => "apple", "b" => "banana");$b = array("a" =>"pear", "b" => "strawberry", "c" => "cherry");$c = $a + $b;var_dump($c);

執行後,此指令碼會顯示:

array(3) {  ["a"]=>  string(5) "apple"  ["b"]=>  string(6) "banana"  ["c"]=>  string(6) "cherry"}

數組中的單元如果具有相同的鍵名和值則比較時相等。

<?php$a = array("apple", "banana");$b = array(1 => "banana", "0" => "apple");var_dump($a == $b); // bool(true)var_dump($a === $b); // bool(false)?>

字串運算子

有兩個字串運算子。第一個是串連運算子(“.”),它返回其左右參數串連後的字串。第二個是串連賦值運算子(“.=”),它將右邊參數附加到左邊的參數後

<?phpecho "thr"."ee";           //prints the string "three"echo "twe" . "lve";        //prints the string "twelve"echo 1 . 2;                //prints the string "12"echo 1.2;                  //prints the number 1.2echo 1+2;                  //prints the number 3?>
<?php $a = '12345';// This works: echo "qwe{$a}rty"; // qwe12345rty, using braces echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used// Does not work: echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed echo "qwe$arty"; // qwe, because $a became $arty, which is undefined?>

邏輯運算子

$a and $b And(邏輯與) TRUE ,如果 $a 與 $b 都為 TRUE 。
$a or $b Or(邏輯或) TRUE ,如果 $a 或 $b 任一為 TRUE 。
$a xor $b Xor(邏輯異或) TRUE ,如果 $a 或 $b 任一為 TRUE ,但不同時是。
! $a Not(邏輯非) TRUE ,如果 $a 不為 TRUE 。
$a && $b And(邏輯與) TRUE ,如果 $a 與 $b 都為 TRUE 。
$a || $b Or(邏輯或) TRUE ,如果 $a 或 $b 任一為 TRUE 。

“與”和“或”有兩種不同形式運算子的原因是它們操作的優先順序不同。

<?php($a = $_GET['var']) || ($a = 'a default');?>
<?php// 下面的 foo() 不會被調用,因為它們被運算子“短路”了。$a = (false && foo());$b = (true  || foo());$c = (false and foo());$d = (true  or  foo());// "||" 的優先順序比 "or" 高$e = false || true; // $e 被賦值為 (false || true),結果為 true$f = false or true; // $f 被賦值為 false [Altair註:"=" 的優先順序比 "or" 高]var_dump($e, $f);// "&&" 的優先順序比 "and" 高$g = true && false; // $g 被賦值為 (true && false),結果為 false$h = true and false; // $h 被賦值為 true [Altair註:"=" 的優先順序比 "and" 高]var_dump($g, $h);?>

以上常式的輸出類似於:

bool(true)bool(false)bool(false)bool(true)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.