Skip to content

How to Fix PHP in_array Returning False for Existing Values

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about How to Fix PHP in_array Returning False for Existing Values. We cover key concepts, practical examples, and best practices.

The Problem

Fix PHP in_array loose comparison issues when checking if values exist in an array — without proper handling, this issue causes subtle bugs that are hard to trace in production.

Quick Fix

Wrong Code

// WRONG — this approach triggers the php-in-array error
<?php
$allowed = [1, 2, 3];
$input = '1';
if (in_array($input, $allowed)) {
    echo 'Access granted';  // Loose comparison! String '1' matches int 1
}

Wrong Output

Access granted
// Security risk: type juggling allowed a string to match an integer without strict check

Right Code

// RIGHT — corrected implementation
<?php
$allowed = [1, 2, 3];
$input = '1';
if (in_array($input, $allowed, true)) {
    echo 'Access granted';
} else {
    echo 'Access denied — type mismatch';
}
\$safe = (int) \$input;
if (in_array(\$safe, \$allowed, true)) {
    echo 'Access granted after cast';
}

Right Output

Access denied — type mismatch
Access granted after cast

Prevention

  • Always pass true as the third argument to in_array for strict comparison
  • Cast user input before comparison when working with typed arrays
  • Be aware that loose in_array can match '0' == false and other dangerous conversions
  • Use strict mode in all permission and security-related code paths

Common Mistakes with in array

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world PHP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does in_array('0', ['abc']) return true in loose mode?

In loose mode, PHP converts 'abc' to 0 in numeric context, so '0' == 0 is true. This is a well-known PHP type juggling pitfall.

Does in_array work with objects?

Yes, but comparison depends on PHP version. In PHP 8+, in_array uses the equality operator rules (object handle comparison) unless strict mode is enabled.

What is the performance impact of strict mode?

Strict mode is slightly faster because PHP skips type conversion. The difference is negligible for most use cases.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro