Current Location: Home> Latest Articles> How to Use PHP's array_filter Function to Filter Out All Non-String Elements from an Array?

How to Use PHP's array_filter Function to Filter Out All Non-String Elements from an Array?

M66 2025-07-18

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.

What is array_filter()?

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.

Practical Example: Filtering Non-String Elements

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.

Method 1: Using is_string as a Callback Function

$filtered = array_filter($data, 'is_string');
<p>print_r($filtered);<br>

Output:

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'));

Method 2: Using an Anonymous Function for More Complex Logic

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>

Real-World Application

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>

Output:

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.

Conclusion

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.