Yerine üçlü operatörü nasıl kullanılır if-else PHP

2 Cevap php

i söylemek kısaltmak veya daha gerekiyor. benim kodları sertleşmesine

Bu benim orijinal kodu:

if ($type = "recent") {
    $OrderType =  "sid DESC";
}elseif ($type = "pop"){
    $OrderType =  "counter DESC";
}else {
    $OrderType =  "RAND()";
}

şimdi nasıl ben bu gibi işaretleri kullanabilirsiniz:

$OrderType = ($type = "recent") ? "sid DESC" : "counter DESC" ;

ben denedim ama operatörleri elseif yazma bilmiyordu

2 Cevap

Bu olarak adlandırılır ternary operator ;-)

Eğer onlardan ikisini kullanabilirsiniz:

$OrderType = ($type == 'recent' ? 'sid DESC' : ($type == 'pop' ? 'counter DESC' : 'RAND()'))

: Bu gibi okunabilir

  • $type ise, 'recent'
  • sonra kullanmak 'sid DESC'
  • else
    • $type ise, 'pop'
    • sonra kullanmak 'counter DESC'
    • else kullanımı 'RAND()'


A couple of notes :

  • You must use == or === ; and not =
  • It's best to use (), to make things easier to read
    • Ve böyle çok fazla üçlü operatörlerini kullanmak gerekir: i düşünmek, anlamak için kod biraz zor yapar


And, as a reference about the ternary operator, quoting the Operators section of the PHP manual :

The third group is the ternary operator: ?:.
It should be used to select between two expressions depending on a third one, rather than to select two sentences or paths of execution.
Surrounding ternary expressions with parentheses is a very good idea.

Bunun yerine bir dava deyimi kullanarak öneririm. Eğer ekstra seçenekler eklemek istediğiniz zaman onu biraz daha okunabilir ama için daha rahat hale getirir

switch ($type)
{
case "recent":
  $OrderType =  "sid DESC"; 
  break;
case "pop":
  $OrderType =  "counter DESC"; 
  break;
default:
   $OrderType =  "RAND()"; 
}