Filter array by prefix - what was that function name?

Let's 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 elements starting from car_? There was a natural function for this, but I forgot her name.

Do you know what function I mean? I know how to do this for / foreach / array _filter. I am quite sure that there was a function for this.

+3
source share
4 answers

Well, you could do this using preg_grep():

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

You can use array_filter(), but you need to pass a test function to it.

+5
source

Regexp requires much more time to process, it is better to use strpos () in this case:

foreach($arr AS $key => $val)
if(strpos(" ".$val, "car_") == 1)     
    $cars[$key] = $val;

:

+2

, :

function filter_by_key_prefix ( $arr, $prefix, $drop_prefix=false ) {
        $params = array();
        foreach( $arr as $k=>$v ) {
            if ( strpos( $k, $prefix ) === 0 ) {
                if ( $drop_prefix ) {
                    $k = substr( $k, strlen( $prefix ) );
                }
                $params[ $k ] = $v;
            }
        }
        return $params;
    }
+1
-1
source

Source: https://habr.com/ru/post/1736032/


All Articles