PHP match
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:
matchifodasi ko‘proq o‘qilishi mumkin bo‘lgan sintaksisga egaswitchdanmatchifodasi qiymatni qaytaradi,switchesa bunday qilmaydimatchifodasi moslik topilgach avtomatik ravishda to‘xtaydi,switchesabreak;talab qiladimatchifodasi qat’iy taqqoslashdan (===) foydalanadi,switchesa 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!
