OneBite.Dev - Coding blog in a bite size

Convert A String To Lowercase In PHP

Code snippet for how to Convert A String To Lowercase In PHP with sample and detail explanation

Working with string data types often requires different manipulations including converting the case of the string. In this article, we will look at how to convert a string to lowercase in PHP. PHP, being a versatile scripting language, provides a simple native function to perform this.

Code snippet: Convert String to Lowercase

Let’s take a look at the PHP code snippet which performs this operation.

<?php
    $string = "HELLO WORLD";
    $lowercaseString = strtolower($string);
    echo $lowercaseString;
?>

When you run this code, the output will be “hello world”.

Code Explanation: Convert String to Lowercase

We start by defining a string variable $string with the value of “HELLO WORLD”. This is done in the first line of the code.

$string = "HELLO WORLD";

Next, we use the PHP function strtolower() to convert the string to lowercase. The strtolower() function is a built-in PHP function specifically designed to turn all alphabetic characters in a string to lowercase. It takes as input the string to be converted.

$lowercaseString = strtolower($string);

Here, the strtolower() function is applied to our predefined string $string and the transformed string is then saved in the new variable $lowercaseString.

Finally, to see the result of our transformation, we use the echo command to print the value of $lowercaseString to screen.

echo $lowercaseString;

The result, as seen on the screen, would be the lowercase version of the original string i.e., “hello world”.

That’s it. The process of converting a string to lower case in PHP is straightforward, thanks largely to PHP’s in-built function strtolower(). Now you can experiment yourself with this function and observe how it behaves with different strings.

php