w3resource

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

PHP Basic Algorithm: Exercise-29 with Solution

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";
?>

Sample 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.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to check if the first appearance of "a" in a given string is immediately followed by another "a".
Next: Write a PHP program to create a string like "aababcabcd" from a given string "abcd".

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.