Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP script to get all keys from an array that starts with a certain string
In PHP, you can filter array keys that start with a specific string using several approaches. Each method offers different advantages depending on your coding style and requirements.
Method 1: Using foreach with explode()
This method uses explode() to split keys by a delimiter and check the first part ?
<?php
$arr_main_array = array('test_val' => 123, 'other-value' => 456, 'test_result' => 789);
$arr_result = array();
foreach($arr_main_array as $key => $value){
$exp_key = explode('_', $key);
if($exp_key[0] == 'test'){
$arr_result[$key] = $value;
}
}
if(!empty($arr_result)){
print_r($arr_result);
}
?>
Array
(
[test_val] => 123
[test_result] => 789
)
Method 2: Using array_filter() with strpos()
A functional approach using array_filter() with ARRAY_FILTER_USE_KEY flag ?
<?php
$array = array('foo-bar' => 1, 'foo-baz' => 2, 'other' => 3, 'foo-test' => 4);
$filtered = array_filter($array, function($key) {
return strpos($key, 'foo-') === 0;
}, ARRAY_FILTER_USE_KEY);
print_r($filtered);
?>
Array
(
[foo-bar] => 1
[foo-baz] => 2
[foo-test] => 4
)
Method 3: Using foreach with strpos()
A procedural approach using strpos() to check if the key starts with the target string ?
<?php
$array = array('test_name' => 'John', 'test_age' => 25, 'user_id' => 100);
$result = array();
foreach ($array as $key => $value) {
if (strpos($key, 'test_') === 0) {
$result[$key] = $value;
}
}
print_r($result);
?>
Array
(
[test_name] => John
[test_age] => 25
)
Method 4: Using ArrayIterator
An object-oriented approach using ArrayIterator for traversing the array ?
<?php
$array = array('foo-item1' => 'value1', 'bar-item2' => 'value2', 'foo-item3' => 'value3');
$i = new ArrayIterator($array);
$result = array();
while ($i->valid()) {
if (strpos($i->key(), 'foo-') === 0) {
$result[$i->key()] = $i->current();
}
$i->next();
}
print_r($result);
?>
Array
(
[foo-item1] => value1
[foo-item3] => value3
)
Comparison
| Method | Performance | Code Style | Best For |
|---|---|---|---|
| foreach + explode() | Good | Procedural | Delimiter-based keys |
| array_filter() | Best | Functional | Simple prefix matching |
| foreach + strpos() | Good | Procedural | Custom logic needed |
| ArrayIterator | Fair | OOP | Object-oriented approach |
Conclusion
Use array_filter() with strpos() for the most efficient and clean solution. Choose foreach approaches when you need additional custom logic during the filtering process.
Advertisements
