Illogical in_array Behavior, not really...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Illogical in_array Behavior, not really...

Post by twinedev »

I wrote a program that extracts data from an image, and one of the things it does is build an array of colors used. I just came across an image that wasn't behaving well, and tracked it down to the following issue. Here is the relavent code:

Code: Select all

echo "Checking Color: "; 
var_dump($strColor);
echo "Against: ";
var_dump($aryColors);

if (!in_array($strColor,$aryColors)) { 
    $aryColors[] = $strColor; 
    echo " ADDING \n"; 
} else { 
    echo " EXISTS \n"; 
}
and here is the output when it hits a "missing" (from the results) color:

[text]Checking Color: string(6) "0e2411"
Against: array(2) {
[0]=>
string(6) "0e2319"
[1]=>
string(6) "243b31"
}
EXISTS [/text]

There is no missing code or logic between the dump of the variables and the if statement that checks for the color in the array.

Now, if I go and change it to have a third parameter of TRUE (to enable STRICT matching) it works fine???

At first I'm thinking "WTF? they are all string(6), what difference does that make...

It finally dawned on me what the problem was... Can you figure it out?
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Illogical in_array Behavior, not really...

Post by AbraCadaver »

Both "0e2411" and "0e2319" are being typecast to int 0.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Illogical in_array Behavior, not really...

Post by Weirdan »

AbraCadaver wrote:Both "0e2411" and "0e2319" are being typecast to int 0.
In the end it's true, but you skipped that part where they were interpreted as numbers in scientific notation with mantissa equal to zero.

@twinedev: why did you store numbers as (hexadecimal) strings?
Post Reply