How to Use in_array in PHP: Syntax and Examples
In PHP, use
in_array(value, array, strict) to check if a value exists in an array. It returns true if found, otherwise false. The optional strict parameter checks type equality.Syntax
The in_array function checks if a value exists in an array.
- value: The item you want to find.
- array: The array to search in.
- strict (optional): If
true, checks type too (default isfalse).
php
bool in_array(mixed $needle, array $haystack, bool $strict = false)Example
This example shows how to check if a number or string is in an array using in_array. It also demonstrates the effect of the strict parameter.
php
<?php $fruits = ['apple', 'banana', 'orange']; // Check if 'banana' is in the array if (in_array('banana', $fruits)) { echo "Banana is in the list.\n"; } else { echo "Banana is not in the list.\n"; } // Check if number 5 is in the array of strings $numbers = ['5', '10', '15']; // Without strict, 5 (int) matches '5' (string) if (in_array(5, $numbers)) { echo "5 found without strict check.\n"; } // With strict, types must match if (!in_array(5, $numbers, true)) { echo "5 not found with strict check.\n"; } ?>
Output
Banana is in the list.
5 found without strict check.
5 not found with strict check.
Common Pitfalls
One common mistake is forgetting the strict parameter, which can cause unexpected matches due to type juggling. For example, 5 (integer) matches '5' (string) if strict is false. Also, in_array only checks values, not keys.
php
<?php // Wrong: no strict, may cause false positives $values = ['0', '1', '2']; if (in_array(false, $values)) { echo "Found false without strict (unexpected).\n"; } // Right: use strict to avoid type confusion if (!in_array(false, $values, true)) { echo "False not found with strict (expected).\n"; } ?>
Output
Found false without strict (unexpected).
False not found with strict (expected).
Quick Reference
Remember these tips when using in_array:
- Use
strict=trueto check both value and type. - It returns
trueorfalse. - It searches only values, not keys.
- Works with any array type: strings, numbers, objects.
Key Takeaways
Use in_array to check if a value exists in an array in PHP.
Set the strict parameter to true to avoid type-related mismatches.
in_array checks values only, not array keys.
It returns true if the value is found, otherwise false.
Always test your code to understand how type juggling affects results.