3v4l.org

run code in 300+ PHP versions simultaneously
<?php $array = [ 'car_porsche', 'caravan', 'car', 'motorcycle_suzuki', 'motorcycle_carabela', ]; $search = 'car'; function keepIfStartsWith_regex(array $haystack, string $needle): array { return preg_grep('/^' . preg_quote($needle, '/') . '/', $haystack); } function removeIfStartsWith_regex(array $haystack, string $needle): array { return preg_grep('/^' . preg_quote($needle, '/') . '/', $haystack, PREG_GREP_INVERT); } function keepIfStartsWith_PHP8(array $haystack, string $needle): array { return array_filter($haystack, fn($v) => str_starts_with($v, $needle)); } function removeIfStartsWith_PHP8(array $haystack, string $needle): array { return array_filter($haystack, fn($v) => !str_starts_with($v, $needle)); } function keepIfStartsWith_PHP7_4(array $haystack, string $needle): array { return array_filter($haystack, fn($v) => strpos($v, $needle) === 0); } function removeIfStartsWith_PHP7_4(array $haystack, string $needle): array { return array_filter($haystack, fn($v) => strpos($v, $needle) !== 0); } function keepIfStartsWith_sub7_4(array $haystack, string $needle): array { return array_filter($haystack, function($v) use($needle) { return strpos($v, $needle) === 0; }); } function removeIfStartsWith_sub7_4(array $haystack, string $needle): array { return array_filter($haystack, function($v) use($needle) { return strpos($v, $needle) !== 0; }); } $functions = [ 'keepIfStartsWith_regex', 'removeIfStartsWith_regex', 'keepIfStartsWith_PHP8', 'removeIfStartsWith_PHP8', 'keepIfStartsWith_PHP7_4', 'removeIfStartsWith_PHP7_4', 'keepIfStartsWith_sub7_4', 'removeIfStartsWith_sub7_4', ]; foreach ($functions as $fn) { echo "$fn: " . json_encode(array_values($fn($array, $search))) . "\n"; }

preferences:
63.86 ms | 410 KiB | 5 Q