In PHP development, it's common to need to filter specific types of data from a mixed-type array—for example: how to keep only the string elements in an array. This is where array_filter() comes into play.
array_filter() is one of PHP's built-in array functions, mainly used to filter elements within an array. It takes an array and an optional callback function and returns a new array containing only those elements for which the callback returns true.
array_filter(array $array, ?callable $callback = null, int $mode = 0): array
$array: The array to be filtered.
$callback: A user-defined function to test each element of the array.
$mode: Optional parameter to specify whether the callback receives the array's keys, values, or both.
Here’s a sample array that includes multiple types of elements:
$data = [
"apple",
42,
"banana",
true,
"cherry",
null,
3.14,
["nested", "array"],
(object) ["name" => "grape"]
];
Our goal is to filter out all non-string values and keep only the string elements.
$filtered = array_filter($data, 'is_string');
<p>print_r($filtered);<br>
Array
(
[0] => apple
[2] => banana
[4] => cherry
)
Note that array_filter() preserves the original array keys. If you want the result to be reindexed, you can use array_values():
$filtered = array_values(array_filter($data, 'is_string'));
If you'd like to extend the logic, such as keeping only strings longer than 5 characters, you can write it like this:
$filtered = array_filter($data, function($item) {
return is_string($item) && strlen($item) > 5;
});
<p>print_r($filtered);<br>
Imagine you're handling an array of form data and need to extract only the user-inputted strings:
$userInput = [
'username' => 'john_doe',
'age' => 28,
'email' => 'john@example.com',
'newsletter' => true,
'website' => 'https://m66.net/profile/john'
];
<p>$stringsOnly = array_filter($userInput, 'is_string');</p>
<p>print_r($stringsOnly);<br>
Array
(
[username] => john_doe
[email] => john@example.com
[website] => https://m66.net/profile/john
)
This way, you can process only the text-type data, such as for sending emails or building database queries.
Using array_filter() together with is_string() allows you to conveniently filter out all string elements from a mixed array. It’s a clean, efficient method ideal for array data cleanup in everyday PHP development.