PHP script to get all keys from an array that starts with a certain string

PHPServer Side ProgrammingProgramming

Method 1

$arr_main_array = array('test_val' => 123, 'other-value' => 456, 'test_result' => 789);
foreach($arr_main_array as $key => $value){
   $exp_key = explode('-', $key);
   if($exp_key[0] == 'test'){
      $arr_result[] = $value;
   }
}
if(isset($arr_result)){
   print_r($arr_result);
}

Method 2

A functional approach
An array_filter_key type of function is taken, and applied to the array elements
$array = array_filter_key($array, function($key) {
   return strpos($key, 'foo-') === 0;
});

Method 3

A procedural approach −

$val_1 = array();
foreach ($array as $key => $value) {
   if (strpos($key, 'foo-') === 0) {
      $val_1[$key] = $value;
   }
}

Method 4

A procedural approach using objects −

Example

$i = new ArrayIterator($array);
$val_1 = array();
while ($i->valid()) {
   if (strpos($i->key(), 'foo-') === 0) {
      $val_1[$i->key()] = $i->current();
   }
   $i->next();
}

Output

This will produce the following output −

Array(test_val => 123
test_result => 789)
raja
Updated on 06-Apr-2020 08:18:02

Advertisements