Filter a multidimensional array (containing elements of irregular depth) using a whitelist of string values
In PHP, handling multidimensional arrays requires a nuanced understanding of how data types are compared internally. A common pattern involves filtering an options array to retain only elements that match specific criteria. In older environments like PHP 5.3, the standard approach was straightforward: use array_intersect(). However, upgrading to PHP 5.4 introduced a breaking change for this specific use case due to a known bug where the function attempts string conversion on nested arrays, triggering a "Array to string conversion" notice.
The underlying issue stems from how array_intersect compares values. When it encounters an array inside the main dataset that does not exactly match a value in the search list (which is expected in irregular structures), PHP tries to cast the array to a string for comparison. Since arrays cannot be directly cast to strings, this results in the warning. This behavior is documented in Bug #60198.
Attempting to suppress this error with @array_intersect is not a viable long-term solution. It obscures debugging information and suggests that the code is working around a bug rather than solving the core logic problem. To handle irregular depth correctly without relying on error suppression, you need to move away from value-based comparison for nested elements and instead focus on key matching or recursive traversal.
Recursive Traversal with Key Matching
The most robust solution involves iterating through the array explicitly while checking if any keys or values match your whitelist. This allows you to bypass the type-conversion logic that triggers the PHP 5.4 error. You can achieve this cleanly using a recursive function that checks both keys and values, ensuring that nested arrays are preserved only if they meet specific criteria.
Here is an implementation that filters $options based on the $lookfor whitelist:
function filterMultidimensional(array $array, array $whitelist): array {
$result = [];
foreach ($array as $key => $value) {
// If the key itself matches a string in the whitelist, keep it
if (is_string($value) && in_array($value, $whitelist, true)) {
$result[$key] = $value;
continue;
}
// If the value is an array, recurse into it
if (is_array($value)) {
$filteredSub = filterMultidimensional($value, $whitelist);
// Only keep the sub-array if it contains matches
if (!empty($filteredSub)) {
$result[$key] = $filteredSub;
}
}
}
return $result;
}
This approach explicitly handles the irregular depth by checking the type of each element before deciding whether to recurse. It avoids the string conversion trap entirely because it never passes an array value to a function expecting strings for direct comparison.
Handling Nested Structures
In your specific example, $options contains a mix of scalar strings and nested arrays like [0] => 123. If your goal is strictly to find elements where the value matches a string in the whitelist (e.g., 'slide' or 'tab'), the recursive function above works perfectly. It extracts the matching scalars while leaving deeper structures intact only if they themselves contain matches later down the line.
If you need to filter based on keys as well, or if you want to ensure that nested arrays are discarded entirely unless they match a specific key pattern, you can adjust the logic inside the recursive step. For instance, you might choose to drop any sub-array that does not immediately contain a matching value, rather than passing it up with partial results.
Trade-offs and Limitations
The primary trade-off of abandoning array_intersect here is performance on very large datasets. Recursive functions in PHP carry overhead due to stack depth and repeated function calls. However, for typical configuration arrays or option setsâwhich are rarely millions of elementsâthe clarity and correctness of the logic outweigh the micro-optimization concerns.
Another consideration is the definition of "match." In your source material, the array contains irregular depths. If a nested array [0] => 123 never contains a string from $lookfor, the recursive approach described above will discard that entire sub-array if you implement strict filtering (e.g., only adding to $result if $filteredSub is not empty). This prevents polluting your result set with irrelevant nested structures.
By explicitly managing the iteration and type checking, you gain full control over how irregular depths are handled. You avoid the brittle behavior of built-in functions that assume homogeneous data types, ensuring your code remains stable across PHP 5.4 and beyond without relying on error suppression or workarounds for known bugs.