Switch case in PHP with variable

6

My question is this, I'm doing a Telegram bot with user help in various cases. I would like to capture a piece of the message that you send me to use it as a variable, that is:

switch($mensaje)
 case '/tiempo Madrid':
    $ciudad="Madrid";
    $horas=FALSE;
    getTiempo($chatId,$ciudad,$horas);
    break;

In this case I would like not to have to write the city directly in the case, but to make a kind of /tiempo $ciudad , whose variable $ciudad can use to call the function getTiempo() and thus not have to write one by one all the cities of the world as different cases.

That is, something like this:

switch($mensaje)
 case '/tiempo $ciudad':
    $horas=FALSE;
    getTiempo($chatId,$ciudad,$horas);
    break;

Thank you very much for the help.

    
asked by Evelyn García 26.07.2018 в 18:10
source

2 answers

2

I do not think you can make the switch with double variable, but look at this alternative: - I suggest you separate the command from the message, that way you can get the data separately and do what you want with them.

    $mensaje = explode(' ', $mensajeUsuario, 2);
    // $mensaje[0]: Representa el comando
    // $mensaje[1]: Representa el mensaje o la otra variable que tu quieres
    switch($mensaje[0])
     case '/tiempo':
        $ciudad = $mensaje[1];
        $horas=FALSE;
        getTiempo($chatId,$ciudad,$horas);
        break;
    
answered by 26.07.2018 / 19:08
source
0

I really do not know a way to dynamically generate the case of a switch, but I think that maybe this alternative can help you. You simply define an array with all the cities (in your case I imagine that they can come from a database), then you go through the array and you are comparing the city of the array with the one of the message, once you find it, the code of the if is executed and the loop stops.

$ciudades = ['Madrid', 'Londres', 'Lima'];

$mensaje = '/tiempo Londres';

foreach($ciudades as $ciudad){
    $comparar = '/tiempo '.$ciudad;
    if($mensaje == $comparar){
        $horas=FALSE;
        echo $ciudad;
        getTiempo($chatId,$ciudad,$horas);
        break;//Evitar que el bucle siga la ejecución una vez se encuentre la ciudad
    }
}

I hope you serve

    
answered by 26.07.2018 в 18:41