PHP

Filter PHP Array Elements by Both Key and Value

Learn to filter array elements based on conditions applied to both their keys and values using `array_filter()` with the `ARRAY_FILTER_USE_BOTH` flag for precise data control.

<?php
$data = [
    'user_id_1' => ['status' => 'active', 'age' => 30],
    'guest_id_2' => ['status' => 'inactive', 'age' => 25],
    'user_id_3' => ['status' => 'active', 'age' => 40],
    'admin_id_4' => ['status' => 'active', 'age' => 35]
];

// Filter for active users with 'user_id' in key and age > 30
$filteredData = array_filter($data, function ($value, $key) {
    return strpos($key, 'user_id') !== false && $value['status'] === 'active' && $value['age'] > 30;
}, ARRAY_FILTER_USE_BOTH);

echo "Filtered Data (Active users with user_id in key and age > 30):
";
print_r($filteredData);

/*
Expected output:
[
    'user_id_3' => ['status' => 'active', 'age' => 40]
]
*/
?>
How it works: The `array_filter()` function iterates over each value in an array, passing it to a user-defined callback function. By adding `ARRAY_FILTER_USE_BOTH` as the third argument, the callback receives both the value and its corresponding key, allowing for more precise filtering logic based on combined criteria.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs