mirror of
https://github.com/TheAlgorithms/PHP.git
synced 2025-07-09 11:13:50 +02:00
33 lines
764 B
PHP
33 lines
764 B
PHP
<?php
|
|
|
|
/**
|
|
* Function returns the total number of consonants present in the given
|
|
* string using a linear search through the string
|
|
*
|
|
* @param string $string
|
|
* @return int
|
|
* @throws \Exception
|
|
*/
|
|
function countConsonants(string $string): int
|
|
{
|
|
if (empty($string)) {
|
|
throw new \Exception('Please pass a non-empty string value');
|
|
}
|
|
|
|
$vowels = ['a', 'e', 'i', 'o', 'u']; // Vowels Set
|
|
$string = strtolower($string); // For case-insensitive checking
|
|
|
|
$consonantCount = 0;
|
|
|
|
for ($i = 0; $i < strlen($string); $i++) {
|
|
if (
|
|
!in_array($string[$i], $vowels) &&
|
|
$string[$i] >= 'a' && $string[$i] <= 'z'
|
|
) {
|
|
$consonantCount++;
|
|
}
|
|
}
|
|
|
|
return $consonantCount;
|
|
}
|