Does not enter the if

Asked

Viewed 54 times

1

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;
}

1 answer

3


Tested with spaces in string, it’s not to come in at all. ' AND' and 'AND' are separate things.

One solution would be this:

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

Here comes another logic problem:

If the value is AND, he won’t be OR, if it’s OR won’t be AND. It will always be true the expression above. Probably you look for it:

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

That can be simplified for this:

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

Or rather, for this:

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

If you want to check so much and how much AND, can use this:

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

See working on IDEONE.


Points of interest:

  • trim serves to remove spaces (or other characters) from the beginning and end of a string;

  • strtoupper returns an uppercase version of string (usually used mb_strtoupper if for accented and/or special characters);

  • in_array checks if a searched value is in any of the positions of a array;

  • when you reverse two logical conditions, you normally need to revise the operator joining the two; example: the inverse of $a=1 OR $b=1 is !$a=1 AND !$b=1 or !($a=1 OR $b=1).

  • i need it to return me a string like : "code = ? AND name = ? OR secao = ?" where the entry is: "code = 1, AND, name = 2, OR, dry = 1"

  • @Rafaelsilva ah, so just leave it out of the loop anyway. But the rest I think is right.

  • Fixed: http://ideone.com/9KCAyw

  • Then, if you test the second value whether it has quotes or not, you can already determine whether it is string or number, if you are going to bind.

  • Perfect guy, thank you very much! To going in leaps and bounds with php rsrs, my forte is java Android. I’m developing my web-server in the nail! Very tasty, I like challenges...

  • All right, any questions about this problem, leave a comment, or others, open a new question, which we can help you with. The most important thing is that you understand what has been done, to reuse knowledge in future situations.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.