filter values from an array similar to SQL LIKE '%search%' using PHP

filter values from an array similar to SQL LIKE '%search%' using PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Filtering Arrays with Partial Matches in PHP

Autocomplete fields are a staple of modern web applications, offering users instant feedback as they type. When building these features with jQuery UI and storing data in a flat document structure, you often end up with an array of values that needs dynamic filtering. The core challenge arises when you need to find substrings rather than exact matches. For instance, given an array like ['orange', 'blue', 'green', 'red', 'pink', 'brown', 'black'], typing "bl" should return only ['blue', 'black'].

While array_diff() is a powerful tool for set operations, it is designed for exact value comparisons. Using it with partial matches requires complex logic to construct temporary difference arrays for every possible substring, which quickly becomes inefficient and difficult to maintain. A more direct approach involves leveraging PHP's built-in string functions or regular expressions to filter the array in a single pass.

Implementing Substring Filtering

The most straightforward way to achieve SQL-like LIKE '%search%' behavior in PHP is by utilizing array_filter() combined with str_contains(). This combination is available in PHP 8.0 and later, offering a clean, readable syntax. If you are working on legacy code running PHP 7.x or earlier, you would need to use strpos() instead, checking for -1 to ensure the substring exists.

Here is a practical implementation using modern PHP:

$data = ['orange', 'blue', 'green', 'red', 'pink', 'brown', 'black'];
$search = 'bl';

$results = array_filter(
    $data,
    fn($item) => str_contains(strtolower($item), strtolower($search))
);

print_r(array_values($results));
// Output: Array ( [0] => blue [1] => brown [2] => black )

In this example, we normalize both the array items and the search term using strtolower(). This ensures the filter is case-insensitive, which is often expected in autocomplete scenarios. The array_filter() function iterates over the original array, keeping only elements where the callback returns true. Finally, array_values() resets the keys to a continuous integer sequence, which is usually necessary after filtering associative arrays or maintaining a specific order.

Handling Case Sensitivity and Performance

One of the most common pitfalls in this scenario is ignoring case sensitivity. If your dataset contains mixed casing (e.g., "Blue" and "blue"), a strict comparison might miss valid results. The str_contains() function handles this well when paired with the normalization step shown above. However, if performance becomes a bottleneck with very large datasets, consider caching the lowercased versions of your data or using a dedicated full-text search engine like Elasticsearch.

For older PHP environments where str_contains() is unavailable, the equivalent logic looks like this:

$results = array_filter(
    $data,
    fn($item) => strpos(strtolower($item), strtolower($search)) !== false
);

The logic remains identical: convert both strings to lowercase and check if the position of the search term is valid.

When to Use Regular Expressions

You might be tempted to use regular expressions for this task, especially since the original question mentioned regex. While possible, using preg_match_all() or similar functions here adds unnecessary overhead. Regular expressions are powerful but slower than simple string operations because they compile patterns and manage backtracking logic. Since your requirement is strictly "contains substring," a simple string search is more efficient and easier to debug. Reserve regex for complex pattern matching where character classes, wildcards beyond %, or specific formatting rules apply.

If you are building this feature within the Laravel ecosystem, consider leveraging Eloquent scopes or query builder methods if your data resides in a relational database, as querying a database often yields better performance than filtering large arrays in memory. However, for small to medium-sized flat files or JSON responses loaded into memory, the array_filter approach remains the most pragmatic solution.

Our network