PHP in_array Loose vs Strict Comparison

I was scratching my head over unexpected results when using the in_array() function. Maybe you are doing the same right now. I recently have an array with stuff in it, like: It’s all ID from the the database results. As you can see, they’re all strings right? See the double quotes. Then I went to […]

Kode

I was scratching my head over unexpected results when using the in_array() function. Maybe you are doing the same right now.

I recently have an array with stuff in it, like:

$array = array(
    "620018.1310100268",
    "620018.1310100187",
    "620125.1250100066",
    "620125.1250100179",
    "620125.1250100178",
    "620084.1280200193"
);

It’s all ID from the the database results. As you can see, they’re all strings right? See the double quotes.

Then I went to check whether the ID « 620018.1310100188 » is present in this array using in_array(). You’d think it’s a no-brainer and expect a false, right? But here’s the twist: thanks to loose comparison, I actually got a surprise true!

Understanding Loose Comparison

Okay, let’s talk about loose comparison – the idea that PHP tries to be the ultimate matchmaker by making values look alike before deciding if they’re a match. When it comes to in_array(), this means it’s more concerned with if values seem similar after a quick makeover, rather than if they’re exactly the same.

Behind the Curtain

Loose comparison decides to throw a party where everyone dresses up the same way. So, it takes « 620018.1310100188 » and « 620018.1310100187 » and gives them matching outfits – in this case, the same numerical value – and voilà, they’re a match! Hence, the unexpected true result that might make you raise an eyebrow or two.

Embracing Strict Comparison

To steer clear of these eyebrow-raising moments, PHP offers the option of playing matchmaker with a twist – strict comparison. This means no quick makeovers; it’s all about true identity. To opt for strict comparison in in_array(), just set the third parameter to true:

$value = "620018.1310100188";
$result = in_array($value, $array, true);

So there you have it! Knowing the difference between loose and strict comparison in PHP can save you from unexpected surprises and make your code more dependable. The next time you’re working with in_array(), take a moment to think about whether you want PHP to throw a quick makeover party or respect each value’s unique identity.