PHP match


ULASHISH

PHP moslik ifodasi

match ifodasi bir nechta shartli tekshiruvlarni boshqarishning yangi usulini taqdim etadi (masalan, switch operator).

match ifodasi bir nechta muqobillarga nisbatan ifodani baholaydi (qattiq taqqoslash yordamida) va qiymatni qaytaradi.

Maslahat: match ifodasi PHP 8.0 da yangi.

Mana match va switch o‘rtasidagi asosiy farqlar:

  • match ifodasi ko‘proq o‘qilishi mumkin bo‘lgan sintaksisga ega switch dan
  • match ifodasi qiymatni qaytaradi, switch esa bunday qilmaydi
  • match ifodasi moslik topilgach avtomatik ravishda to‘xtaydi, switch esa break; talab qiladi
  • match ifodasi qat’iy taqqoslashdan (===) foydalanadi, switch esa erkin taqqoslashdan (==) foydalanadi

Moslik uchun sintaksis

$result = match($expression) {
  condition1 => returnvalue1,
  condition2 => returnvalue2,
  condition3, condition4 => returnvalue3,
  default => defaultvalue,
}

Maslahat: Standart qo‘l mos kelmaydigan barcha ifodalarni ushlaydi.

Quyidagi misol quyidagi misolga teng switch sahifa, lekin bu yerda biz match ifodasidan foydalanamiz:

Misol

$favcolor = "red";

$text = match($favcolor) {
  "red" => "Your favorite color is red!",
  "blue" => "Your favorite color is blue!",
  "green" => "Your favorite color is green!",
  default => "Your favorite color is neither red, blue, nor green!",
};

echo $text;
O‘zingiz sinab ko‘ring »


Bir nechta qiymatlarni moslashtirish

Agar xohlasangiz match ifodasi bir xil kod bloki uchun bir nechta qiymatlarga mos kelishi mumkin ularni vergul bilan guruhlang, shunday qilib:

Misol

Bir nechta qiymatlarni moslang:

$d = 3;

$text = match($d) {
  1, 2, 3, 4, 5 => "The week feels so long!",
  6, 0 => "Weekends are best!",
  default => "Invalid day",
};

echo $text;
O‘zingiz sinab ko‘ring »

Standart kalit so‘z

match ifodasida kerak shart bo‘lsin yoki birlamchi holatga mos keladigan uni boshqaring.

Agar mos kelsa va birlamchi holat bo‘lmasa, match ifoda UnhandledMatchError istisnosini chiqaradi.

Misol

Bu UnhandledMatchError istisnosini keltirib chiqaradi:

$favcolor = "pink"; // no conditions will match this

try {
  $text = match($favcolor) {
    "red" => "Your favorite color is red!",
    "blue" => "Your favorite color is blue!",
    "green" => "Your favorite color is green!",
  };
} catch (\UnhandledMatchError $e) {
  var_dump($e);
}

echo $text;
O‘zingiz sinab ko‘ring »

W3Schools Pathfinder

Yutuqlaringizni kuzating – bu bepul!