- strpos: documentation ( source)
- var_export: documentation ( source)
- array_filter: documentation ( source)
- current: documentation ( source)
<?php
$haystack = "I like cats.";
$needles = ['cat' => 0, 'dog' => 1];
function inefficient(string $haystack, array $needles) {
$qualifiers = array_filter(
$needles,
fn($k) => strpos($haystack, $k) !== false,
ARRAY_FILTER_USE_KEY
);
if (!$qualifiers) {
throw new Exception('No needles were found in the haystack');
}
return current($qualifiers);
}
try {
var_export(inefficient($haystack, $needles));
} catch (Exception $e) {
echo $e->getMessage();
}