Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array by prefix - what was that function's name?

Tags:

arrays

php

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.

like image 907
Pekka Avatar asked Mar 09 '10 00:03

Pekka


People also ask

How do you filter an array?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

Does filter mutate array?

filter creates a new array, and mutationFilter does not. Although in most cases creating a new array with Array. filter is normally what you want. One advantage of using a mutated array, is that you can pass the array by reference, without you would need to wrap the array inside another object.

What is array filter PHP?

The array_filter() function filters the values of an array using a callback function. This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array.


2 Answers

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.

like image 95
cletus Avatar answered Oct 11 '22 07:10

cletus


Regexp takes much more time to process, it`s better to use strpos() in this case:

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

This also works with keys:

like image 37
InVeX Avatar answered Oct 11 '22 09:10

InVeX