PHP - get all keys from a array that start with a certain string

后端 未结 9 1354
日久生厌
日久生厌 2020-11-30 00:09

I have an array that looks like this:

array(
  \'abc\' => 0,
  \'foo-bcd\' => 1,
  \'foo-def\' => 1,
  \'foo-xyz\' => 0,
  // ...
)
9条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 00:57

    In addition to @Suresh Velusamy's answer above (which needs at least PHP 5.6.0) you can use the following if you are on a prior version of PHP:

     0,
        'foo-bcd' => 1,
        'foo-def' => 1,
        'foo-xyz' => 0,
    );
    
    $filtered = array_filter(array_keys($input), function($key) {
        return strpos($key, 'foo-') === 0;
    });
    
    print_r($filtered);
    
    /* Output:
    Array
    (
        [1] => foo-bcd
        [2] => foo-def
        [3] => foo-xyz
    )
    // the numerical array keys are the position in the original array!
    */
    
    // if you want your array newly numbered just add:
    $filtered = array_values($filtered);
    
    print_r($filtered);
    
    /* Output:
    Array
    (
        [0] => foo-bcd
        [1] => foo-def
        [2] => foo-xyz
    )
    */
    

提交回复
热议问题