Ik heb een 'groot' script:

<?php
if($controle->soort == "1"){
// error A \\
}elseif($controle->soort == "2"){
// error A \\
}elseif($controle->soort == "3"){
// error A \\
}

// Of het volgende:

if( ($controle->soort == "1") || ($controle->soort == "2") || ($controle->soort == "3") ){
// error A \\
}
?>

Nu zou ik dit willen oplossen op de volgende manier (o.i.d.):

<?php
if($controle->soort == ("1" || "2" || "3") ){
// error A \\
}
?>


Maar voorzover ik weet is dit niet mogelijk. Weet iemand anders een manier hoe ik dit script 'flink' kan inkorten?
Ik zou het met een switch oplossen:
<?php
switch($controle->soort){
case 1:
case 2:
case 3:
// error A
break;
case 4:
// etc
break;
}
?>
Het mooiste, maak een method of functie. Maar dit kan ook:

<?php
if($controle->soort >= 1 && $controle->soort <= 3) {
print "Yay";
} else {
print "Nay";
}
?>

Of als je wat meer hipster wilt zijn:
<?php
if(in_array($controle->soort, range(1, 3))) {
print "Yay";
} else {
print "Nay";
}
?>

En nog meer, omdat het kan:
<?php
for($found = false, $i = 1; $i <= 3 && !$found; ++$i) {
if($i == $controle->soort) {
print "Yay";
$found = true;
} else if($i == 3) {
print "Nay";
}
}
?>

<?php
if(preg_match("#^([123]{1})$#", $controle->soort) == 1) {
print "Yay";
} else {
print "Nay";
}
?>

<?php
if(filter_var($controle->soort, FILTER_VALIDATE_INT,
array(
'options' => array(
'min_range' => 1,
'max_range' => 3
),
'flags' => FILTER_NULL_ON_FAILURE
)
) !== null) {
print "Yay";
} else {
print "Nay";
}
?>

<?php
if(max(3, $controle->soort) == 3 && min($controle->soort, 1) == 1) {
print "Yay";
} else {
print "Nay";
}
?>
<?php
if(count(array_diff((array)$controle->soort, array(1,2,3))) == 0) {
print "Yay";
} else {
print "Nay";
}
?>

<?php
if(array_key_exists($controle->soort, array_flip(range(1, 3)))) {
print "Yay";
} else {
print "Nay";
}
?>

<?php
if(array_search($controle->soort, array(1, 2, 3)) {
print "Yay";
} else {
print "Nay";
}
?>
Of zo:

<?php
$error_a = array(1, 2, 3);
if(in_array($controle->soort, $error_a){
// error A!
}
?>

Reageren