$a = 5; $b = 9; 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"; endif; 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"; }
while (expr) statement while (expr): statement ... endwhile;
<?php $i = 0; do { echo $i; } while ($i > 0); ?>
for 循環是 PHP 中最複雜的循環結構。php
for (expr1; expr2; expr3) statement for (expr1; expr2; expr3): statement; ... endfor;
foreach 語法結構提供了遍歷數組的簡單方式。python
foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement
用 list() 給嵌套的數組解包mysql
<?php $array = [ [1, 2], [3, 4], ]; foreach ($array as list($a, $b)) { // $a contains the first element of the nested array, // and $b contains the second element. echo "A: $a; B: $b\n"; } ?>
break 結束當前 for,foreach,while,do-while 或者 switch 結構的執行。laravel
break 能夠接受一個可選的數字參數來決定跳出幾重循環。git
continue 在循環結構用用來跳過本次循環中剩餘的代碼並在條件求值爲真時開始執行下一次循環。面試
continue 接受一個可選的數字參數來決定跳過幾重循環到循環結尾。默認值是 1,即跳到當前循環末尾。redis
switch 語句相似於具備同一個表達式的一系列 if 語句。sql
<?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; } ?>
require 和 include 幾乎徹底同樣,除了處理失敗的方式不一樣以外。docker
require 在出錯時產生 E_COMPILE_ERROR 級別的錯誤。 換句話說將致使腳本停止而 include 只產生警告(E_WARNING),腳本會繼續運行。數據庫
require_once 語句和 require 語句徹底相同,
惟一區別是 PHP 會檢查該文件是否已經被包含過,若是是則不會再次包含。
#語法 if(條件){ 條件爲true時執行此代碼 }elseif(condition){ 條件爲true時執行此代碼 }else{ 條件爲false時執行此代碼 } #分支語句實例 $t = date("H"); if($t<"10"){ echo "Have a good morning!"; }elseif($t<"20"){ echo "Have a good day!"; }else{ echo "Have a good night!"; }
while (條件爲真) { 要執行的代碼; } #例子,while是先判斷後執行,變量是控制器必定要注意改變。 $myvar = 10; while($myvar>0){ echo $myvar; $myvar--; }
#do...while(稱爲當次循環,先執行後判斷) $myvar = 10; do{ echo $myvar; $myvar--; }while($myvar>0);
#for語句是很是經典的 for($i=0;$i<10;$i++){ echo $myvar; }
#foreach適用於數組 $colors = array("reb","green","blue","yellow"); foreach($colors as $key => $value){ echo $value; }
goto mylabel; echo "Hello World!"; mylabel: echo "Moments";
#將字符串進行倒排輸出 $myvar = "abcd"; function reverse($myvar, $flag=-1){ if($flag<strlen($myvar)-1){ $flag++; $myvar = reverse(substr($myvar,0,$flag).substr($myvar,strlen($myvar)-1).substr($myvar,$flag,strlen($myvar)-1-$flag), $flag); } return $myvar; } echo reverse($myvar);
$conn = mysql_connect("localhost","root","123456") or die("Error");
//不報告全部錯誤 error_reporting(~E_ALL); //報告運行時錯誤 error_reporting(E_ERROR | E_WARNING | E_PARSE);
try{ //可能出現錯誤或異常的代碼 //catch 捕獲 Exception是php已定義好的異常類 } catch(Exception $e){ echo $e->getMessage(); //對異常處理,方法: //一、本身處理 //二、不處理,將其再次拋出 }