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
Selected Reading
Search for PHP array element containing string?
In PHP, you can search for array elements containing a specific string using several methods. The most common approaches include preg_match() for pattern matching, array_filter() for functional filtering, and simple string functions like strpos().
Using preg_match() with foreach
The preg_match() function allows pattern−based searching with regular expressions ?
<?php
$subject = array('JavaScript', 'Java', 'PHP language', 'Python Language');
$valueToSearch = 'Language';
$result = array();
foreach($subject as $key => $value) {
if(preg_match("/\b$valueToSearch\b/i", $value)) {
$result[$key] = $value;
}
}
print_r($result);
?>
Array
(
[2] => PHP language
[3] => Python Language
)
Using array_filter() with strpos()
A simpler approach using array_filter() for case−insensitive substring matching ?
<?php
$subject = array('JavaScript', 'Java', 'PHP language', 'Python Language');
$valueToSearch = 'Language';
$result = array_filter($subject, function($item) use ($valueToSearch) {
return stripos($item, $valueToSearch) !== false;
});
print_r($result);
?>
Array
(
[2] => PHP language
[3] => Python Language
)
Using array_filter() with preg_match()
Combining array_filter() with preg_match() for more concise code ?
<?php
$subject = array('JavaScript', 'Java', 'PHP language', 'Python Language');
$valueToSearch = 'Language';
$result = array_filter($subject, function($item) use ($valueToSearch) {
return preg_match("/\b$valueToSearch\b/i", $item);
});
print_r(array_values($result)); // Re-index the array
?>
Array
(
[0] => PHP language
[1] => Python Language
)
Comparison
| Method | Use Case | Case Sensitive |
|---|---|---|
preg_match() |
Pattern matching, word boundaries | Configurable (/i flag) |
stripos() |
Simple substring search | No |
strpos() |
Simple substring search | Yes |
Conclusion
Use preg_match() for complex pattern matching and stripos() for simple case−insensitive substring searches. The array_filter() approach provides cleaner, more functional code compared to manual loops.
Advertisements
