using array_search or loop in PHP to find the position of a key
Solution 1:
Another way is to use preg_match()
and a simple foreach
. This method avoid the iteration of all items of the array and stops when a match is found.
/**
* Returns the index of the first match or false if not found.
*/
function arraySearch(array $array, string $search): int|false
{
foreach ($array as $key => $value) {
if (preg_match('~' . $search . '$~',$value)) {
return $key;
}
}
return false;
}
$unique_domains = [
'www.crownworldwide.com',
'www.acquisition.gov',
'www.hemisphere-freight.com',
'www.businessinsider.com',
'www.oceansidelogistics.com',
'mixjet.aero',
'www.airindiaexpress.in',
'rlglobal.com',
'www.metroshipping.co.uk',
'www.flexport.com'
];
var_dump(arraySearch($unique_domains, 'flexport.co')); // bool(false)
var_dump(arraySearch($unique_domains, 'flexport.com')); // int(9)
- live demo PHP 8.0
- live demo PHP 7.4