Comparator does not work! =

2

I'm trying to recognize when a record in my BD does not match a word.

I have the following code that works well when $ client is equal to Day , but does not work if $ client equals day

   elseif (strpos($cliente, 'Dia') !== false or strpos($cliente, 'plaza') !== false) {
              echo "background:#c31434;";
              }

I tried to do it the other way around and it does not work either

elseif (strpos($cliente, 'Dia') == true or strpos($cliente, 'plaza') == true) {
                  echo "background:#c31434;";
                  }

I have also tried to do it like @Hector Lopez says in this way, and it does not work the same as in the case above.

elseif ($cliente == 'dia' || $cliente == 'plaza') {
                  echo "background:#c31434;";
                  }

This is my complete if

<?php if(strpos($cliente, 'Lupa') !== false or strpos($cliente, 'lupa') !== false or strpos($cliente, 'Tifer') !== false){
                  echo "background:#1474c3;";
                  }
                  elseif ($cliente =='dia' || $cliente =='plaza') {
                  echo "background:#c31434;";
                  }
                  else{
                  echo "background:#778998;";
                  }; 
    
asked by Tefef 16.10.2018 в 10:30
source

1 answer

1

I would solve this in a more flexible , creating an array where the keys would be the value of the color, and each key has a sub-array with the values to look for. In this way you will not need to do so many if and if in the future you have to incorporate more values / colors just modify the array and the code would still work only.

For comparison, instead of strpos , you use strripos , which does the same, but is case insensitive , that is, insensitive to capital letters / lowercase.

Let's see:

$cliente="diA";
$arrColors=array('#1474c3'=>array('lupa','tifer'),"#c31434"=>array('dia','plaza'));
/*Valor por defecto*/
$bgColor="#778998";
foreach ($arrColors as $k=>$arrValues){
    if (is_array($arrValues)){
        foreach ($arrValues as $value) {
            if(stripos($cliente, $value) !== false){
                $bgColor=$k;
            }
        }
    }
}
echo "background:$bgColor;";

Exit:

background:#c31434;

Now:

  • test yourself with other values
  • consider an evolution of the code. Imagine that it is now required to find the value 'amarillo' and assign it the background color #FFFF00 ... You should only add this to $arrColors : '#FFFF00'=>array('amarillo')
answered by 16.10.2018 / 12:21
source