Search code examples
phparraysfilteringprefixpreg-grep

Native function to filter array by prefix


Say I have an array with the following members:

car_porsche
car_mercedes
car_toyota
motorcycle_suzuki
motorcycle_honda
motorcycle_motoguzzi

How can I get an array with all the elements starting with car_? There was a native function for this but I forgot its name.

Do you know which function I mean? I know how to do it with for/foreach/array_filter. I'm quite sure there was a function for exactly this.


Solution

  • Well, you could do it using preg_grep():

    $output = preg_grep('!^car_!', $array);
    

    You could use array_filter() too but you have to pass a test function into that.