运算符
算术运算符
- “+”,”-“,”*”,”/“ 加减乘除
$num1 = 4;
$num2 = 2;
$num1+$num2 //输出6,相当于4+2
$num1-$num2 //输出2,相当于4-2
$num1*$num2 //输出8,相当于4*2
$num1/$num2 //输出2,相当于4/2
- “%” 取模运算
$num1 = 3;
$num2 = 2;
$num1+$num2 //输出1,相当于3/2,取到余数1
- “++”,”—“自增自减运算
$num1 = 4;
$num2 = $num1++; //等同于$num2 = $num; $num1+1
//输出$num1=5,$num2=4
$num2 = ++$num1; //等同于$num1+1;$num2 = $num1
//输出$num1=5,$num2=5
$num1 = 4;
$num2 = $num1--; //等同于$num2 = $num; $num1-1
//输出$num1=3,$num2=4
$num2 = ++$num1; //等同于$num1-1;$num2 = $num1
//输出$num1=3,$num2=3
- 幂运算使用运算符’**’,需要php5.6以上版本
$num1 = 4**2;// 输出16,计算4的2次方
字符串运算符
- 字符串运算符用”.”连接
$str1 = 'Hello';
$str2 = 'World';
echo $str1.$str2;//输出 Hello World
赋值运算符
- 赋值使用 ‘=’
$num = 4;//将4赋值给$num1
$num += 4;//$num = $num+4
$num -= 4;//$num = $num-4
$num *= 4;//$num = $num*4
$num /= 4;//$num = $num/4
$str1 = 'Hello';
$str1 .= 'World';//输出Hello World 等同于 $str1= $str1.'World'
比较运算符
比较运算符: 返回布尔值,常用于流程控制中
- ‘<’,’>’,’>=’,’<=’
$num1 = 3;
$num2 = 2;
$num1 > $num2 //输出1 ,表示true
$num1 >= $num2 //输出1 ,表示true
$num1 < $num2 //无输出,表示false
$num1 <= $num2 //无输出,表示false
- ‘==’,’===’,’!=’,’!==’
‘==’ 要求两边值相等;’===’要求两边值相等并且类型相同
$num1 = 3;
$num2 = '3';
$num1 == $num2 //输出1 ,表示true
$num1 === $num2 //输出0 ,false
$num1 != $num2 //无输出,表示false
$num1 !== $num2 //输出1 ,表示true
- <=>太空船 php7.1以上版本试用
$num1 = 3;
$num2 = 5;
echo $num1<=>$num2 //输出-1
//如果$num1>$num2 输出大于0的整数
//如果$num1<$num2 输出小于0的整数
//如果$num1=$num2 输出等于0的整数
分支流程控制
- 单分支 if
$num1 = 5;
if ($num1 > 3) {
echo $num1, '大于3';
}
简化版:去掉大括号
if($num1 > 3):
echo $num1, '大于3';
endif;
- 多分支 if … elseif …else
$num1 = 5;
if ($num1 > 5) {
echo $num1, '大于5';
} elseif($num1<5) {
echo $num1,'小于5';
}else {
echo $num1,'等于5';
}
简化版:去掉大括号
if ($num1 > 5) :
echo $num1, '大于5';
elseif($num1<5) :
echo $num1,'小于5';
else :
echo $num1,'等于5';
endif;
- swicth 语句
$num1 = 5;
switch ($num1) {
case $num1 > 5:
echo $num1, '大于5';
break;
case $num1 < 5:
echo $num1, '小于5';
break;
default:
echo $num1, '等于5';
}
简化版:去掉大括号
switch ($num1):
case $num1 > 5:
echo $num1, '大于5';
break;
case $num1 < 5:
echo $num1, '小于5';
break;
default:
echo $num1, '等于5';
endswitch;
循环
- 入口判断型 while
$nums = [1, 2, 3, 4, 5];
$i = 0;
while ($i < count($nums)) {
echo $nums[$i];
$i++;
}
简化版:去掉大括号
while ($i < count($nums)) :
echo $nums[$i];
$i++;
endwhile;
- 出口判断型 do…while :如果不满足条件至少会循环一次
$i = 0;
do {
echo $nums[$i];
$i++;
} while ($i > count($nums));
简化版:去掉大括号
暂无
- for循环
$nums = [1, 2, 3, 4, 5];
for ($i = 0; $i < count($nums); $i++) {
echo $num[$i];
}
简化版:去掉大括号
for ($i = 0; $i < count($nums); $i++) :
echo $num[$i];
endfor;
- break 与 continue
$nums = [1, 2, 3, 4, 5];
$i = 0;
do {
if ($i > 3) break;
echo $nums[$i];
$i++;
} while ($i < count($nums));
$nums = [1, 2, 3, 4, 5];
for ($i = 0; $i < count($nums); $i++) :
if ($i === 3) continue;
echo $nums[$i];
endfor;
include 与 require
- include是在运行阶段包含,所以可以用在if中;require不可以
- include运行出错,程序可以继续执行;require不可以
- include_once,require_once只包含一次
- require= include…eixt;
//引入文件的方式
include 'header.php';
require 'header.php';