Alternate between capitalizing and lowercase each letter

Is there a way to capitalize every other letter in a string? I am familiar with converting to lowercase or uppercase, as well as capitalizing the first letter, but I am unsure about how to handle every other one. Just for clarification, I have provided examples below. This question pertains to developing a cipher that my son and I are experimenting with - not for normal text formatting purposes.

pizza -> PiZzA
party -> PaRtY
popcorn -> PoPcOrN

Answer №1

$outputString = '';
foreach(str_split($inputString) as $pos => $character) {
    $outputString .= ($pos % 2) ? strtolower($character) : strtoupper($character);
}

CodeBox.

Answer №2

Here is a method I will attempt:

$string = join(
    array_map(
        function($s){
            return ucfirst($s);
        },
        str_split($string,2)
    )
);

Alternatively, as a one-liner:

$string = join(array_map(function($s){return ucfirst($s);}, str_split($string,2)));

You can make the function more general by passing the chunk length to be capitalized as a parameter and letting the function handle the rest. The logic behind this algorithm is simple:

  • str_split returns an array of strings with the specified length,
  • the array_map function applies the transformation to each chunk, and
  • the join method combines the strings into the final result string.

The completed function looks like this:

function camelCycles($string, $period) {
  return join(
     array_map(
       function($s){
         return ucfirst($s);
       },
       str_split($string, $period)
     )
  );
}

This function utilizes only built-in constructs and should therefore run efficiently.

EDIT:

For compatibility with PHP 5.0 onward (since str_split was introduced in php5), here is an alternative function that doesn't use lambda expressions:

function camelCycles($string, $span) {
  return join(array_map('ucfirst', str_split(strtolower($string), $span)));
}

Answer №3

To modify the text, I propose dissecting it into an array and then piecing it back together:

function changeToLowerCase($str){
     $temp = explode('',$str);
     $result = '';
     foreach($temp as $i=>$val){
         if($i%1 == 0) $result .= strtolower($val);
         else $result .= strtolower($val);
     } 
     return $result;
}

Answer №4

function modifyString($str)
{
    $result = '';
    $flag = false;

    foreach(str_split($str) as $char)
    {
        $result .= ($flag ? strtoupper($char) : $char);
        $flag = !$flag;
    }

    return $result;
}

echo modifyString("hello there, mr person sir");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for inserting a php variable into an html document

I am trying to figure out how to export a variable from a php file into an html file. The php file I'm working with is example.php and it contains the following code: <?php $array= ['one','two']; ?> The html file is named ...

Please refresh the page after acknowledging the error

I am facing an issue with my PHP page that triggers a javascript alert upon encountering an error. if (strpos($this->color,':') !== false) { echo '<script type="text/javascript">alert("Please use the RBG format of 255:2 ...

Error in Reactjs in production mode: net::ERR_CERT_COMMON_NAME_INVALID

My Reactjs application is deployed on a Linux server and can be access at I am using PHP APIs to fetch data, which are also hosted on the same server and accessible through However, when trying to fetch data from the API, I receive an error in the consol ...

Calculate the total sum of values in a MySQL column and then group the results

I'm currently working on a quiz website and looking to create a leaderboard. The user scores are stored in a database table named 'user_record' with the following structure: 'user_id' - varchar(254) -holds the user id for a score ...

What advantages does a DoublyLinkedList offer when used in PHP?

Recently, I stumbled upon the PHP-SPL data structures and decided to explore the first one: the doubly linked list. While I have a basic understanding of a linked list, grasping the concept of a doubly linked list made me wonder: What practical application ...

What is the best way to retrieve a specific section of text from a variable that holds XML information in PHP?

As a newcomer to PHP programming, I need assistance. I have a variable called $output that holds an XML response obtained from a server. How can I extract the "value" data and assign it to a different variable? For instance, let's say we want to assig ...

Utilizing a PHP-scripted multidimensional array in an AJAX success function

I've encountered an issue while trying to access a multidimensional array passed to my AJAX success function. Here's how I'm sending the data: $response = array(); $response['message']['name'] = $name; $response['m ...

Is this jQuery script not functioning properly?

I came across this code on jsfiddle, and I really want to incorporate it into my PHP file. However, when I tried to do so, it didn't work even though I simply copied and pasted the code without making any changes. Here is my code: <!DOCTYPE html& ...

"How to use PHP cURL to automatically follow redirects and retrieve the final result

Are you experiencing issues while trying to access the following URLs? If so, you may also need to check the results on this URL: Using PHP cURL, attempts have been made to retrieve these results, but unfortunately, the page turns out to be empty without ...

eliminate the backslash from a JSON string

After receiving a JSON string from a server response, I need to reformat it as follows: "{ { "id": "1", "mid": "1", "num": "1", "type": "wgp", "time_changed": "time", "username": "aaa" } } Below is my attempt at reformatting the string: $str = substr($s ...

Enhance the appearance of a multidimensional array using main and sub-main styling

Struggling with a new challenge here... after spending hours trying to wrap my head around it, I'm still stuck. Let's dive in... I've worked with arrays before, but only simple ones like this: $arr = array('1', '2', &apo ...

Using PHP to iterate through an array and output the values within a

Hey there! I have a question about incorporating PHP foreach and echo into JavaScript to make it dynamic. Here is the current static JavaScript code: <script type="text/javascript"> $(document).ready(function(){ $('input[type="checkbox"]&ap ...

Using the div id within JavaScript to create a new Google Maps latitude and longitude

Here is my code for locating an IP using Google Maps. I am trying to set new google.maps.LatLng('< HERE >') to <div id="loc"></div>. How can I achieve this where the result will be 40.4652,-74.2307 as part of #loc? <scrip ...

What is the best way to determine the number of non-empty entries within a PHP array?

Consider: [uniqueName] => Array ( [1] => uniqueName#1 [2] => uniqueName#2 [3] => uniqueName#3 [4] => uniqueName#4 [5] => [6] => ...

CodeIgniter throwing a date error when it is being hosted

Attention: The date() function may not work properly due to the system's timezone settings. It is essential to specify the date.timezone setting or utilize the date_default_timezone_set() function. If you are still encountering this warning after impl ...

retrieving the outcome from a PHP script invoked through Ajax

Having trouble transferring the results of a PHP script to HTML input fields This is my PHP script: $stmt->execute(); if ($stmt->rowCount() > 0){ $row = $stmt->fetch(PDO::FETCH_ASSOC); echo 'Located: ' . $row[&ap ...

What is preventing me from assigning $_SERVER['DOCUMENT_ROOT'] as an attribute?

How come I am unable to assign the value of $_SERVER['DOCUMENT_ROOT'] as an attribute? class foo { private $path = $_SERVER['DOCUMENT_ROOT']; // This line causes an error private $blah; public function __construct() { // Some code her ...

Remove the first character if the variable starts with a dot

Seeking a foolproof solution that is simple. I have a $keyword variable and I need to filter it by removing the first character if it is a '.' Otherwise, I want to leave it unchanged. I am hesitant to attempt this on my own because in the past, I ...

Can someone assist me with navigating through my SQL database?

Struggling with a script that searches multiple fields in the same table, I need it to return results even if one or three parameters are left blank. My attempts using PHP and MySql have been fruitless so far, which is why I am reaching out to the experts ...

My WordPress loadmore function is not providing any additional posts

Hey everyone, I'm facing a Wordpress issue that I can't seem to resolve. I've checked other posts but haven't found the solution yet. So, I decided to share my code here and seek help. My problem is with trying to load more posts using ...