Code Logo

Value in Array

Published at24 Jul 2026
PHP Data Structures Easy 0 views
Like0

Write a PHP function that checks if a value exists in an array using a manual loop, without the built-in in_array() function.

Use a foreach loop to iterate through array elements. Compare each element with the target using strict comparison (===). Return true as soon as a match is found. If the loop finishes without finding a match, return false.

Strict comparison (===) checks both value and type, unlike loose comparison (==) which performs type coercion. For example, 0 == '0' is true but 0 === '0' is false.

Edge cases include empty arrays (return false immediately), the target at the first position (best case O(1)), and type-sensitive matching where the string '5' should not match the integer 5.

The time complexity is O(n) in the worst case. Space complexity is O(1).

The linear search algorithm is the simplest approach for finding an element in an unsorted array. It checks each element in order and returns upon finding a match. For sorted arrays, binary search would be more efficient, but linear search works for all cases.

The early return optimization immediately exits the function when a match is found, providing O(1) best-case performance when the target is at the beginning of the array.

Example Input & Output

Example 1
Input
0, [1,2]
Output
false
Example 2
Input
3, [1,2,3,4,5]
Output
true
Example 3
Input
5, []
Output
false
Example 4
Input
5, [5]
Output
true
Example 5
Input
6, [1,2,3,4,5]
Output
false

Algorithm Flow

Recommendation Algorithm Flow for Value in Array
Recommendation Algorithm Flow for Value in Array

Solution Approach

Write a PHP function that checks if a value exists in an array using a manual loop, without the built-in in_array() function.

Use a foreach loop to iterate through array elements. Compare each element with the target using strict comparison (===). Return true as soon as a match is found. If the loop finishes without finding a match, return false.

Strict comparison (===) checks both value and type, unlike loose comparison (==) which performs type coercion. For example, 0 == '0' is true but 0 === '0' is false.

Edge cases include empty arrays (return false immediately), the target at the first position (best case O(1)), and type-sensitive matching where the string '5' should not match the integer 5.

The time complexity is O(n) in the worst case. Space complexity is O(1).

Best Answers

php - Approach 1
<?php
function contains($target, $arr) {
    foreach($arr as $e){if($e===$target)return true;}return false;
}