w3resource

PHP Exercises: Create a new string using 3 copies of the first 2 characters of a given string

PHP Basic Algorithm: Exercise-82 with Solution

Write a PHP program to create a new string using 3 copies of the first 2 characters of a given string. If the length of the given string is less than 2 use the whole string.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that repeats the first two characters of a string
function test($s1)
{ 
    // Initialize a variable to store the repeated characters
    $extra_Front = "";
    
    // Check if the length of $s1 is less than 2
    if (strlen($s1) < 2)
    {
        // If so, concatenate $s1 with itself and return the result
        return $s1 . $s1 . $s1;
    }
    // If the length of $s1 is 2 or more
    else
    {
        // Extract the first two characters of $s1
        $extra_Front = substr($s1, 0, 2);
        // Concatenate the extracted characters with themselves and return the result
        return $extra_Front . $extra_Front . $extra_Front;
    }
}

// Test the 'test' function with different strings, then display the results
echo test("abc") . "\n";
echo test("Python") . "\n";
echo test("J") . "\n";
?>

Sample Output:

ababab
PyPyPy
JJJ

Flowchart:

Flowchart: Create a new string using 3 copies of the first 2 characters of a given string.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to concat two given strings. If the given strings have different length remove the characters from the longer string.
Next: Write a PHP program to create a new string from a given string. If the two characters of the given string from its beginning and end are same return the given string without the first two characters otherwise return the original string.

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.