LAST UPDATED: AUGUST 4, 2021
How to convert a string to lowercase in PHP?
Answer: Using strtolower()
function
The strtolower()
is a pre-defined PHP function that can be used to convert the string to lowercase. This function takes a string and returns a new string having lowercase alphabetic characters.
Example: Using strtolower()
function
In the given example, we have used the strtolower()
function to convert all the alphabet characters of the given string into the lowercase.
<!DOCTYPE html>
<html>
<head>
<title>Convert string to lowercase</title>
</head>
<body>
<?php
$str = "WELCOME TO STUDYTONIGHT";
$return_str = strtolower($str);
echo $return_str;
?>
</body>
</html>
Output
welcome to studytonight
Without using library function
In the above example, we have used the pre-defined function to convert the string to the lowercase. Here we are going to convert the given string to the lower case without using the library function.
We have first converted the given string into an array of characters then we have calculated the ASCII value using the ord()
function. As we know that in ASCII code, the lowercase characters come exactly 32 places after the uppercase. So we have added the 32 to the ASCII value and converted it back into the alphabet characters using the chr()
function.
Example: Without library function
In the given example, we have converted the given string into the lowercase without using the predefined function.
<!DOCTYPE html>
<html>
<head>
<title>Convert string to lowercase</title>
</head>
<body>
<?php
function lowercase($str)
{
$val = str_split($str);
$result = '';
for ($i = 0; $i < count($val); $i++) {
$char = ord($val[$i]);
if ($val[$i] >= 'A' && $val[$i] <= 'Z'){
$result .= chr($char + 32);
}
else{
$result .= $val[$i];
}
}
return $result;
}
$text = "Welcome to STUDYTONIGHT";
echo lowercase($text);
echo "<br>";
?>
</body>
</html>
Output
welcome to studytonight
Conclusion
In this lesson, we have learned how to convert the given string into the lowercase. Here, we have discussed two methods. First, we have used the pre-defined function strtolower()
to convert all the alphabet characters to lowercase. Then we have converted the string into the lowercase without using the predefined function.