8 March 2024

To filter an array by key using a pattern in PHP, you can use functions like array_filter() and regular expressions. In this example, preg_match() is used to check if the key matches the defined pattern. The ARRAY_FILTER_USE_KEY flag tells array_filter() to pass the keys to the callback function instead of the values.

Source code viewer
  1. // Sample array
  2. $array = array(
  3. 'key1' => 'value1',
  4. 'key2' => 'value2',
  5. 'foo' => 'bar',
  6. 'test123' => 'value3',
  7. 'xyz' => 'value4'
  8. );
  9.  
  10. // Define your pattern (regular expression)
  11. $pattern = '/^key\d+$/'; // Matches keys like 'key1', 'key2', etc.
  12.  
  13. // Filter the array by key using the defined pattern
  14. $result = array_filter(
  15. $array,
  16. function($key) use ($pattern) {
  17. return preg_match($pattern, $key);
  18. },
  19. ARRAY_FILTER_USE_KEY
  20. );
Programming Language: PHP