Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Search for partial value match in an Array in PHP
In PHP, you can search for partial value matches in an array using various methods. The most common approaches include strpos() with loops, array_filter() with callback functions, and preg_grep() for pattern matching.
Using strpos() with foreach Loop
The simplest method uses strpos() to check if a substring exists within each array element −
<?php
$arr = array('apple', 'banana', 'cherry', 'grape');
$searchTerm = 'an';
$results = array();
foreach ($arr as $value) {
if (strpos($value, $searchTerm) !== false) {
$results[] = $value;
}
}
if (empty($results)) {
echo 'No matches found.';
} else {
echo "'" . $searchTerm . "' was found in: " . implode(', ', $results);
}
?>
'an' was found in: banana
Using array_filter() with Callback
A more functional approach uses array_filter() with an anonymous callback function −
<?php
$fruits = array('apple', 'apricot', 'banana', 'orange');
$searchTerm = 'ap';
$filtered = array_filter($fruits, function($item) use ($searchTerm) {
return strpos($item, $searchTerm) !== false;
});
echo "Fruits containing '" . $searchTerm . "': " . implode(', ', $filtered);
?>
Fruits containing 'ap': apple, apricot
Using preg_grep() for Pattern Matching
For more advanced pattern matching, use preg_grep() with regular expressions −
<?php
$names = array('John', 'Jane', 'Bob', 'Alice');
$pattern = '/^J/i'; // Names starting with 'J' (case-insensitive)
$matches = preg_grep($pattern, $names);
echo "Names starting with 'J': " . implode(', ', $matches);
?>
Names starting with 'J': John, Jane
Case-Insensitive Search
To perform case-insensitive partial matching, use stripos() instead of strpos() −
<?php
$colors = array('Red', 'GREEN', 'blue', 'Yellow');
$search = 'red';
$result = array_filter($colors, function($color) use ($search) {
return stripos($color, $search) !== false;
});
echo "Colors containing '" . $search . "': " . implode(', ', $result);
?>
Colors containing 'red': Red
Conclusion
Use strpos() with loops for simple searches, array_filter() for functional programming style, and preg_grep() for complex pattern matching. Choose stripos() for case-insensitive searches.
