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.
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.
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With