Skip to content
PHP Logo

How can one search for partial strings within an array in PHP?

When searching for partial strings within an array in PHP, you can use the array_filter() function along with a custom callback function. This callback function will check if the partial string is present in each element of the array and return true if it matches. By using array_filter(), you can create a new array containing only the elements that match the partial string.

php
<?php
// Sample array
$array = ['apple', 'banana', 'orange', 'grape', 'kiwi'];

// Partial string to search for
$partialString = 'an';

// Custom callback function to check for partial string match
$filteredArray = array_filter($array, function($element) use ($partialString) {
    return strpos($element, $partialString) !== false;
});

// Output the filtered array
print_r($filteredArray);
?>