Mads Nielsen
Mads Nielsen

Reputation: 106

0 found in empty array

I am trying to generate random numbers with the rand() function, and making sure they are not in the excArray.

If i do print_r(array_values($excArray)) it returns Array ( [0] => ) which means it is empty (right?)

But when i do in_array($randInt, $excArray)($randInt is = 0) or simply echo in_array(0, $excArray); it returns 1

Here is my code:

function generateCode($char, $int, $prefix, $len, $lenMin, $lenMax, $exclude, $array){
    do{
        $code = "";
        $i = 0;
        $excArray = explode(",", $exclude);
        echo in_array(0, $excArray);
        exit();
        while($i++ < $int){
            do {
                $randInt = rand(0,1);
                    echo $randInt;
            }while(in_array($randInt, $excArray));
            $code .= $randInt;
        }

So why does echo in_array(0, $excArray); echo 1?

Thanks!

Upvotes: 0

Views: 60

Answers (1)

deceze
deceze

Reputation: 522135

Array ( [0] => ) means there one item which prints as an empty string, probably null or false or... an empty string. Use var_dump instead of print_r to see more information about its actual type. From there you're probably encountering funky behaviour related to type casting when comparing numbers to strings... Either use in_array(.., .., true) for strict comparisons, or figure out what your empty item is in that array and avoid creating it in the first place.

Upvotes: 3

Related Questions