PHP Exercises: Create a new string made of every other character starting with the first from a given 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:
Flowchart:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics