Using Loops and String Manipulation in PHP to Extract Characters from Sentences

Introduction

Hello, and welcome to today's PHP lesson! We are going to unravel an intriguing challenge that will refine our skills in string manipulation. This lesson will place particular emphasis on loops. Prepare yourself for an exciting adventure as we explore how to extract odd-indexed characters from each word in a sentence, but only if the word has an even number of characters. Sounds exciting? Let's dive in!

Task Statement

The task we'll be demonstrating is as follows: We will work with a string representing a sentence in which words are separated by spaces. Your challenge involves creating a PHP function that identifies the odd-indexed characters of words that have an even number of characters and then combines these characters into a single string, maintaining the order in which they appeared in the sentence.

Consider this example: "PHP8 programming language is versatile." The word PHP8 has 4 characters (an even number), and we'll select the odd-indexed characters from this word, specifically, H and 8. Similarly, we'll select a, g, a, and e from language, s from is, and e, s, t, l, and . from versatile.. We'll skip the word programming because it has an odd length.

If our function is working correctly, it should return "H8agaesestl.". Isn't it fascinating to see what we can extract from a simple sentence?

Solution Building: Step 1

We will start by splitting the sentence into words using the explode function. This will help us create an array containing all the words in the sentence.

PHP
<?php
function solution($sentence) {
    $words = explode(" ", $sentence);
    // we will proceed progressively
}
?>

Solution Building: Step 2

We now introduce loops: an outer loop that iterates over every single word, and an if condition that verifies whether a word has an even length. We can determine this by checking whether the length of the word modulo 2 equals zero. If it does, the word has an even length!

PHP
<?php
function solution($sentence) {
    $words = explode(" ", $sentence);

    foreach ($words as $word) {
        if (strlen($word) % 2 == 0) {  // check if the length of the word is even
            // we are building up our solution gradually
        }
    }
}
?>
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal