w3resource

PHP Exercises: Create a new string made of every other character starting with the first from a given string


29. Every Other Character String

Write a PHP program to create a new string made of every other character starting with the first from a given string.

Sample Solution:

PHP Code :

<?php
// Define a function that extracts characters at even positions in a string
function test($s)
{
    // Initialize an empty string to store the result
    $result = "";

    // Iterate through the string
    for ($i = 0; $i < strlen($s); $i++) {
        // Check if the index is even and append the character to the result
        if ($i % 2 == 0) {
            $result .= substr($s, $i, 1);
        }
    }

    // Return the final result
    return $result;
}

// Test the function with different input strings
echo test("Python")."\n";
echo test("PHP")."\n";
echo test("JS")."\n";
?>

Explanation:

  • Function Definition:
    • The test function takes a single parameter, $s, which is a string. The function extracts and returns characters located at even index positions.
  • Initialize Result Variable:
    • An empty string $result is initialized to store characters found at even positions.
  • Iterate Through String:
    • A for loop iterates through each character of the string $s from index 0 to strlen($s) - 1.
  • Check for Even Indexes:
    • Inside the loop, the code checks if the index $i is even using the condition $i % 2 == 0. If true, it appends the character at index $i to $result.
  • Return Final Result:
    • After the loop completes, $result contains all characters from even positions in the string, which is then returned.

 

Output:

Pto
PP
J

Visual Presentation:

PHP Basic Algorithm Exercises: Create a new string made of every other character starting with the first from a given string.

Flowchart:

Flowchart: Create a new string made of every other character starting with the first from a given string.

For more Practice: Solve these Related Problems:

  • Write a PHP script to generate a new string composed of every second character from the original, starting with the first character.
  • Write a PHP function to iterate through the characters of a string and selectively concatenate every other character into a new string.
  • Write a PHP program to create an alternate-character string using a loop and index checking, without using built-in slicing.
  • Write a PHP script to use array conversion of a string and then reassemble every other element into a resulting string.

Go to:


PREV : First "a" Followed Immediately by Another "a".
NEXT : Build Progressive String Pattern.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.