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

Logic to convert the given string in uppercase string without using the library function in PHP.
Submitted by Bhanu Sharma, on August 08, 2019 [Last updated : March 13, 2023]

Converting String to Uppercase W/O Using Library Function

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

PHP code to convert string to uppercase w/o using library function

//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);
            $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 = "";
echo upperCase($text);
echo "<br>";




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 Upper Case characters come exactly 32 places before the lower case equivalent, we subtract 32 from 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.

PHP String Programs »


Comments and Discussions!

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

© some rights reserved.