Home » PHP » PHP Examples

PHP program to convert string to lowercase without using the library function

Converting string to lowercase in PHP: Here, we are going to learn the logic to convert the given string in lowercase string without using the library function in PHP.
Submitted by Bhanu Sharma, on August 08, 2019

Given a string and we have to convert it into lowercase string without using any library function.

PHP code:

<?php
//function definition
//this function accepts a string/text, converts
//text to lowercase and return the lowercase converted string
function lowercase($str)
{
	$chars  = str_split($str);
	$result = '';

	//loop from 0th character to the last character
	for ($i = 0; $i < count($chars); $i++) {
		//extracting the character and getting its ASCII value
		$ch = ord($chars[$i]);

		//if character is a lowercase alphabet then converting 
		//it into an lowercase alphabet
		if ($chars[$i] >= 'A' && $chars[$i] <= 'Z')
			$result .= chr($ch + 32);
		else
		$result .= $chars[$i];
	}
	//finally, returning the string
	return $result;
}

//function calling
$text = "HELLO WORLD";
echo lowercase($text);
echo "<br>";

$text = "Hello world!";
echo lowercase($text);
echo "<br>";

$text = "[email protected]";
echo lowercase($text);
echo "<br>";

?>

Output

hello world
hello world!
[email protected]

Code explanation:

We convert the string ($str) into an array of characters ($chars) then calculate their ASCII value using ord() function. Since we know that in ASCII, the lowercase characters come exactly 32 places after the uppercase equivalent, we add 32 to the ASCII value and then convert it back to the character using the chr() function. The output is stored in the $result variable.

This program is a good proof of concept.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.