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

后端 未结 9 1349
日久生厌
日久生厌 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:50

    From PHP5.6, the array keys can be the sole subject of the filtration by using the ARRAY_FILTER_USE_KEY constant/flag.

    From PHP7.4, arrow functions make custom functions more concise and allow values to be passed into the custom function's scope without use().

    From PHP8, str_starts_with() can take the place of strpos(...) === 0

    Code: (Demo)

    $array = [
      'abc' => 0,
      'foo-bcd' => 1,
      'foo-def' => 1,
      'foo-xyz' => 0,
    ];
    
    $prefix = 'foo';
    
    var_export(
        array_filter(
            $array,
            fn($key) => str_starts_with($key, $prefix),
            ARRAY_FILTER_USE_KEY
        )
    );
    

    Output:

    array (
      'foo-bcd' => 1,
      'foo-def' => 1,
      'foo-xyz' => 0,
    )
    

提交回复
热议问题