1.运算符的优先级
2.PHP中的部分运算符
(1)算术运算符
<?php
echo (5 % 3)."\n"; // prints 2
echo (5 % -3)."\n"; // prints 2
echo (-5 % 3)."\n"; // prints -2
echo (-5 % -3)."\n"; // prints -2
?>
(2)赋值运算符
基本的赋值运算符是"="。一开始可能会以为它是"等于",其实不是的。它实际上意味着把右边表达式的值赋给左边的运算数。 赋值运算表达式的值也就是所赋的值。
<?php
$a = 'a';
$a .= ' b';//字符串运算符
var_dump($a);//printf ab
?>
(3)比较运算符
<?php
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1
// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1
// Objects
$a = (object) ["a" => "b"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 0
$a = (object) ["a" => "b"];
$b = (object) ["a" => "c"];
echo $a <=> $b; // -1
$a = (object) ["a" => "c"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 1
// only values are compared
$a = (object) ["a" => "b"];
$b = (object) ["b" => "b"];
echo $a <=> $b; // 1
?>
(4)逻辑运算符
(5)字符串运算符
有两个字符串(string)运算符。第一个是连接运算符("."),它返回其左右参数连接后的字符串。第二个是连接赋值运算符(".="),它将右边参数附加到左边的参数之后。
<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>
(6)位运算符
3.流程控制
(1)if-else-if
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
(2)switch
<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
(3)for
<?php
/* example 1 */
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
(4)foreach
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // 最后取消掉引用
?>
(5)while
<?php
/* example 1 */
$i = 1;
while ($i <= 10) {
echo $i++; /* the printed value would be
$i before the increment
(post-increment) */
}
(6)do-while
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);//输出0
?>
4.用if对留言内容进行简单的检查
?php
$content = $_POST['content'];
$user = $_POST['user'];
if($content == '' ){
die('留言内容不能为空');
}
if($user == ''){
die('留言人不能为空');
}
/*
先循环读取禁止使用的用户名,使用if语句,
逐一的与提交的留言人进行对比,
任何一个相同,代表禁止使用的用户名
*/
$n = ["张三","李四","王五"];
foreach($n as $name){
if($user == $name){
die('禁止使用的用户名');
}
}
var_dump($content,$user);
?>