tags:

views:

90

answers:

3

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.

+3  A: 

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.

cletus
A: 

I think you can use array_filter() for that purpose.

henasraf
A: 

You can write a simple routine which gives you the option of dropping the prefix in your returned array:

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;
    }
Pete B