Constrol Structures

if

else ifelseif 都可以。

$score = 95;
if ($score > 90) {
  var_dump("A");
} else if ($score > 80) {
  var_dump("B");
} elseif ($score > 80) {
  var_dump("C");
} else {
  var_dump("F");
}

switch

case 為字串也可以,每個條件要加 break 跳出。

$paymentStatus = "1"; // both 1 or "1" works

switch ($paymentStatus) {
  case 1:
    var_dump("Success");
    break;
  case 2:
    var_dump("Denied");
    break;
  default:
  var_dump("Unknown"); }

match

  • match 是一種 expression,總是會回傳值。
  • 與 switch 比起來, match 需要型態一致,不會主動 typecasting
$paymentStatus = 2;

$message = match ($paymentStatus) {
  1 => "Success",
  2 => "Denied",
  default => "Unknown"
};

while

$a = 1;
while ($a <= 15) {
  echo $a;
}
do {
  echo $a;
  $a++;
} while ($a <= 15);

for loop

跟 C 類似

for ($i = 1; $i <= 15; $i++) {
  echo $i;
}

跳過特定條件 continue,跳出 break

for ($i = 1; $i <= 15; $i++) {
  if ($i == 6) {
    continue;
  }
  echo $i;
}

Foreach Loop

$names = ["John", "Jane", "Sam"];

foreach ($names as $name) {
  var_dump($name);
}

獲取 key 的方式

$names = ["John", "Jane", "Sam"];

foreach ($names as $key => $name) {
  echo "key: {$key} => " . "{$name}";
  echo "<br>";
}

Function


// 回傳 string
function getStatus($paymentStatus, $showMessage = true): string

// 不回傳
function getStatus($paymentStatus, $showMessage = true): void

// 可以透過 union,回傳可以是字串或者null
function getStatus(int|float $paymentStatus, bool $showMessage = true): ?string

// 接受各種 data type
function getStatus(mixed $paymentStatus, bool $showMessage = true): ?string

Misc

Strict Types

放在最前面,每個檔案都要各別放。

declare(strict_types=1);

Constants

define('FOO', 'hello world'); // can not use in the class

const FOO = "hello world"; // they cannot be conditionally defined within the flow of program execution. They must have an initial value at the time of declaration.

Unset

$name = "john";
echo $name;
unset($name); // delete variable
echo $name;


$names = ["john", "jane", "bobo"];
echo $names;
unset($names[1]); // delete variable
$names = array_values($names); // reindex array to fill the gap 🔥
echo $names;

Alternative if statement

另一種 if else 寫法,夾雜 HTML 時好用。

<?php $permission=2; ?>

<?php if ($permission === 1) : ?>
    <h1>Hello Admin</h1>
<?php elseif ($permission === 2) : ?>
    <h1>Hello OP</h1>
<?php else : ?>
    <h1>Hello Others</h1>
<?php endif; ?>

Include files

<?php include_once 'nav.php'; ?>
  • require 與 include 處理 error 不同
  • require 會傳出 fatal
  • include 只會傳出 warning

Variadic Function

function sum(int|float ...$nums) { // syntax
  var_dump($nums);
  return array_sum($nums);
}
echo sum(5,2,9,1);

Named Arguments

function sum($a, $b) {
    var_dump($a, $b);
    return $a+$b;
};

echo sum(b: 5, a: 2);

使用情境,只設定部分,如下例子:

// setcookie(
//     string $name,
//     string $value = "",
//     string $expires_or_options = 0,
//     string $path = "",
//     string $domain = "",
//     bool $secure = false,
//     bool $httponly = false
// ): bool

setcookie("hello", httponly: true); // named arguments

Arrow Functions

$mul = function($num) {
  return $num *2;
};

echo $mul(5); // dollar sign

Arrow Functions example

$mul = fn ($num) => $num * $multiplier; // similar to javascript

Callable

TODO

Pass by Reference

$cup = 'empty';
function fillCup(&$cupParam) { // add & before param! 🔥
  $cupParam = 'filled';
}
fillCup($cup);
echo $cup;

Files

$directory = scandir(__DIR__);
mkdir('foo');
rmdir('foo');

if (file_exists('example.txt')) { // exists
  echo 'File found!';
}

if (file_exists('example.txt')) {
	echo filesize('example.txt'); // size. cached
	file_put_contents('example.txt', 'hello world!');
}

clearstatcache(); // clear cache to update filesize

file_get_contents('example.txt');

Destructuring Arrays

[$var1, $var2] = $array; 這樣就把 $array 數組的第一個元素賦值給了 $var1,第二個元素賦值給了 $var2。 🔥

解構的主要用途之一是在函數返回多個值的時候。比如,如果你的函數需要返回多個數據,你可以將這些數據放在一個 Array 中,然後通過解構將數據分配給不同的變數。這樣可以提高代碼的可讀性和可維護性。

另外,解構還可以用於遍歷 Array 或對象的元素,以及將函數的多個返回值解構為變數。

// 解構數組
$array = [1, 2];
[$var1, $var2] = $array;
echo $var1; // 輸出 1
echo $var2; // 輸出 2

// 函數返回多個值
function getValues() {
    return [1, 2];
}
[$var1, $var2] = getValues();
echo $var1; // 輸出 1
echo $var2; // 輸出 2

// 遍歷數組元素
$array = [[1, 2], [3, 4]];
foreach ($array as [$a, $b]) {
    echo $a; // 輸出 1,然後 3
    echo $b; // 輸出 2,然後 4
}

Arrays Common Methods

$users = ['john', 'jane', 'bob', null];

// 1. isset null 或者 false 會失敗

if (isset($users[0])) {
	echo "User Found!";
}


// 2. array_key_exists 只要有值,不管 null 或者 false 都會成立

if (array_key_exists(3, $users)) {
	echo "User Found!";
}

// 3. array_filter 剔除 null 或者 false

$users = array_filter($users);
echo '<pre>';
print_r($users);
echo '</pre>';


// 4. array_filter callback

$users = array_filter(
    $users,
    fn($users) => $users != 'bob'
);
echo '<pre>';
print_r($users);
echo '</pre>';

// 5. array_map
$users = array_map(
    fn($user) => strtoupper($user),
    $users,
);

// 6. merge
$users = ['john', 'jane', 'bob'];

$users = array_merge(
    $users,
    ['Sam', 'Jessica'],
);

// 7. sort
sort($users);