I'm currently struggling with a PHP issue : I'd like to use the str_starts_with function (AFAIK available from PHP 8.0) to check if a given phone number actually starts with a phone code (all the phone codes are defined in an array).
According to documentation, it seems the str_starts_with function doesn't support arrays as parameter, that's why I'm trying to find another way to solve my problem.
I used the foreach loop to check all the codes one-by-one, and see if the given phone number actually starts with one of the codes contained in the array. But it seems that combining foreach, array and str_starts_with is not always possible.
The greatest advantage of the str_starts_with function is that it can handle codes of various lengths : for example, there are phone codes with one digit (+1 : Canada, U. S. A., and many other), two digits (+33 : France), three digits (+353 : Ireland).
Here is what I tried :
$tel = '+33601020304';
$tel = preg_replace('/[^0-9]/', '', $tel); //33601020304
$tel = ltrim($tel, '0'); //33601020304
$tel_array = array('32' => 'Belgique', '33' => 'France', '34' => 'Espagne', '41' => 'Suisse', '44' => 'Royaume-Uni', '49' => 'Allemagne');
foreach($tel_array as $pays => $code)
{
str_starts_with($tel, $pays);
echo $pays.'_'.$code.'<br />';
}
If the number starts with one of the codes from the array, I'd like to return the country where the number comes from (name of the country also contained in the array). Else, I would like to return an error.
Instead of that, for the moment, I get this :
32_Belgique 33_France 34_Espagne 41_Suisse 44_Royaume-Uni 49_Allemagne
How could I get and display the country to which the number is assigned, and display an error else ?