¿Hay un atajo para activar el resultado de fn (case_value)?

switch (true) {
    case array_key_exists('view', $load):
        # code...
        break;
    case array_key_exists('model', $load):
        # code...
        break;
    default:
        # code...
        break;
}

this code works fine. but this is laborious. what is it shortcut? like this

switch ($a = array_key_exists($a, $load)) {
    case 'view':
        # code...
        break;
    case 'model':
        # code...
        break;
    default:
        # code...
        break;
}

But this not works

preguntado el 28 de mayo de 14 a las 12:05

your second switch can only be true or false no view, model... -

No, it is not possible to express it any other way using switch. -

2 Respuestas

There is no shortcut for such an operation in PHP.

However, the original code should probablemente ser escrito como

if (array_key_exists('view', $load)) {
    // ..
} else if (array_key_exists('model', $load)) {
    // ..
} else {
    // ..
}

contestado el 28 de mayo de 14 a las 12:05

#check if exists
if(array_key_exists($a, $load))  

#check what exists
switch ($a) {
    case 'view':
        # code...
        break;
    case 'model':
        # code...
        break;
    default:
        # code...
        break;
}

#case for nothing matched
else{
  # code...
}

contestado el 28 de mayo de 14 a las 14:05

This doesn't have the same results as the OPs code (which is an abuse of switch vs. if/else-if.) - user2864740

@ user2864740, This doesn't have the same results as the OPs code, please elaborate more, e.g. what's the difference? as I can't see any. - Bolu

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.