Do not enter if

1

I have a function but the same is not entering the if ...

/**
 * funcao que trocas os valores por "?"
 * @param type $condicao : ex "codigo = 1, AND, nome = 2, OR, secao = 1" ou "codigo = 1, AND, nome = rafael" ou "codigo = 1";
 * @return type ex: "codigo = ? AND nome = ? OR secao = ?" 
 */
function prepareCondReadInterrogacao($condicao) {
    $val = explode(",", $condicao);
    $temp = "";
    foreach ($val as $value) {
        if (!strcmp($value, "AND") || !strcmp($value, "OR")) {
            echo 'entrei';
            $val2 = explode("=", $value);
            $val2[1] = " ?";
            $value = implode("=", $val2);
        }
        $temp .= $value . " ";
    }

    return $temp;
}
    
asked by anonymous 22.01.2017 / 22:15

1 answer

3

If you tried with spaces in string , it is not to enter yourself. ' AND' and 'AND' are different things.

One solution would be this:

if (!strcmp(trim($value), 'AND') || !strcmp(trim($value), 'OR')) { 

Here's another logic problem:

If the value is AND , it will not be OR , if it is OR it will not be AND . The expression above will always be true. You're probably looking for this:

if (!strcmp(trim($value), 'AND') && !strcmp(trim($value), 'OR')) {

That can be simplified to this:

if (!trim($value)=='AND') && !trim($value)=='OR') {

Or rather, for this:

if (!in_array($value, array('AND','OR'))) {

If you want to check both and and AND , you can use this:

if (!in_array(strtoupper($value), array('AND','OR'))) {

See working at IDEONE .


Points of Interest:

  • When you reverse two logical conditions, you usually need to revise the operator joining the two; example: the inverse of trim is strtoupper or mb_strtoupper .

22.01.2017 / 22:21