Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Induvidual elements to Uppercase

Tags:

php

I am working through the Coderbyte challenges as I am teaching myself some PHP.

I have been working through the below challenge (link below)

Coderbyte Challenge

I have got the to below and I a bit confused as it now capitalises each letter of the array rather than the letters selected in the 'if statement'.

I am eager to learn and dont just simply want an answer without an explanation. If you could tell me where I am going wrong and if I am doing things in a long winded approach.

Thanks for your help.

<?php 

function LetterChanges($str) {  

// code goes here
$str = strtolower($str);
$strArray = str_split($str);

for($i = 0; $i < strlen($str); $i++){

  ++$strArray[$i];

 if($strArray[$i] == "aa"){
   $strArray[$i] = "A";
 }
 elseif($strArray[$i] == "e" || "i" || "o" || "u"){
   $strArray[$i] = strtoupper($strArray[$i]);
 }

 }

 return implode ($strArray); 

 }

 // keep this function call here  
 // to see how to enter arguments in PHP scroll down
 echo LetterChanges(fgets(fopen('php://stdin', 'r')));  

 ?> 
like image 634
Tomaff Avatar asked Jan 31 '26 07:01

Tomaff


1 Answers

You can use this code

function LetterChanges($str){
    $arr = array();
    $strlen = strlen( $str );
    for( $i = 0; $i <= $strlen; $i++ ) {
        $char = substr( $str, $i, 1 );
        ++$char;

        if($char == "a" || $char == "e" || $char== "i" || $char== "o" || $char== "u"){
            $char = strtoupper($char);
        }
        if($char == "aa"){
            $char = 'A';  //When we increase Z it becomes aa so we changed it to A 
        }
        $arr[] = $char;
    }
    //print_r($arr);
    echo implode("",$arr);
}

LetterChanges('hello*3'); 

Explanation

In for loop get each character separately in an array then increase it by one then in that increased character we check for vowels if they present then we change them uppercase and again change that array to simple string.

like image 79
Sunil Pachlangia Avatar answered Feb 02 '26 20:02

Sunil Pachlangia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!