true giving problem (bug) in code [closed]

2

Good evening guys, I was developing a script in php and when I put the true being passed by parameter to a function into an array dynamically, it gave a bug. I can not explain the right bug, but the function works pretty much like array_unique . if set true it acts as array_unique , if false it simply repeats what was passed to it.

Follow the code below:

function random_caractere_v2($veredito) {
                 if($veredito) {
                    $elemento = func_get_args();
                    $array = array();
                    foreach ($elemento as $indice => $valor) {
                        if(in_array($valor, $array)) {
                            continue;
                        }
                        if(!in_array("$valor", $array)) {
                            $array[] = $valor;

                        }
                    }
                    print_r($array);
                 }
                 if(!$veredito) {
                     $elemento = func_get_args();
                     print_r($elemento);
                 }
              }


random_caractere_v2(true,'lapiseira','colchao','caderno','quimica','quimica');

I managed to solve the problem using unset to get the index that caused the problem, but I'm curious to find out why the bug.

    
asked by anonymous 30.11.2018 / 02:13

1 answer

1

The problem is in the func_get_args function. It takes all arguments passed to its function, including the initial Boolean. You have to remove this boolean from your array and then work with the new elements.

function random_caractere_v2($veredito) {
    if ($veredito) {
        $elemento = func_get_args();
        // remove o primeiro elemento
        array_shift($elemento);

        $array = array();
        foreach ($elemento as $indice => $valor) {
            if(in_array($valor, $array)) {
                continue;
            }

            $array[] = $valor;
        }

        print_r($array);
    }

    if (!$veredito) {
        $elemento = func_get_args();
        // remove o primeiro elemento
        array_shift($elemento);
        print_r($elemento);
    }
}

But, another way to do this is, from PHP 5.6, use the ... operator, where you can define the fixed arguments and then whatever is variable. For example:

function random_caractere_v2($veredito, ...$elements) {
    if ($veredito) {
        $array = array();
        foreach ($elements as $idx => $value) {
            if (in_array($value, $array)) {
                continue;
            }

            $array[] = $value;
        }

        return $array;
    }

    return $elements;
}

That will do the same thing as the other function does, but in a more elegant way.

    
30.11.2018 / 22:12