Appearance
search a php array for partial string match
You can use the array_filter() function in PHP to search through an array and return only the elements that contain a certain string. For example, to search for all elements in an array $arr that contain the string "example", you can use the following code:
Example of searching for all elements in an array in PHP
php
<?php
$arr = ['Example1', 'example2', 'exAmple3', 'other'];
$result = array_filter($arr, function ($element) {
return strpos($element, "example") !== false;
});
foreach ($result as $element) {
echo $element . "\n";
}
// Output:
// example2
?>The array_filter() function takes two arguments: the array you want to search, and a callback function that will be applied to each element in the array. The callback function should return true if the element should be included in the result, and false if it should be excluded. In this case, the callback function uses the strpos() function to check if the string "example" is present in the element, and returns true if it is.
This will return the array with matching element(s) You can also use preg_grep() function to search for partial string match
Example of using preg_grep() function to search for partial string match in PHP
php
<?php
$arr = ['Example1', 'example2', 'exAmple3', 'other'];
$result = preg_grep('/example/i', $arr);
foreach ($result as $element) {
echo $element . "\n";
}
// Output:
// Example1
// example2
// exAmple3
?>The preg_grep() function takes two arguments: a regular expression pattern to match and the array to search. This function will return an array containing all elements that match the pattern.