In this tutorial, We will learn PHP to get all array keys starting with a certain string. It's a simple example of PHP array filter only certain keys. 



Example 1:

<?php
  
    $myArray = [
        'hd-1' => 'One',
        'hd-2' => 'Two',
        '3' => 'Three',
        'hd-4' => 'Four',
    ];
  
    $result = [];
    $startWith = 'hd';
    foreach($myArray as $key => $value){
        $exp_key = explode('-', $key);
        if($exp_key[0] == $startWith){
            $result[] = $value;
        }
    }
  
    print_r($result);
  
?>


Output:

Array
(
    [0] => One
    [1] => Two
    [2] => Four
)



Example 2:

<?php
  
    $myArray = [
        'hd-1' => 'One',
        'hd-2' => 'Two',
        '3' => 'Three',
        'hd-4' => 'Four',
    ];
  
    $resultArray = array_filter($myArray, function($key) {
       return strpos($key, 'hd-') === 0;
    }, ARRAY_FILTER_USE_KEY);
  
    print_r($resultArray);
  
?>



Output:

Array
(
    [0] => One
    [1] => Two
    [2] => Four
)