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

Changing over the string to capitalized in PHP: Here, we will gain proficiency with the rationale to change over the given string in a capitalized string without utilizing the library function in PHP.

Given a string and we need to change over it into a capitalized string without utilizing any library function.

PHP code:

<?php
//function definition
//this function accepts a string/text, converts
//text to uppercase and return the uppercase converted string
function upperCase($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 uppercase 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 upperCase($text);
echo "<br>";

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

$text = "Hello@123.com";
echo upperCase($text);
echo "<br>";

?>

Output

HELLO WORLD
HELLO WORLD!
HELLO@123.COM

Code Explanation:

We convert the string ($str) into a variety of characters ($chars) at that point figure their ASCII value utilizing ord() function. Since we realize that in ASCII, the Upper Case characters come precisely 32 places before the lower case proportional, we subtract 32 from the ASCII value and afterwards convert it back to the character utilizing the chr() function. The output is put away in the $result variable.

This program is a decent verification of the idea.

Leave a Comment

error: Alert: Content is protected!!