w3resource

PHP Exercises: Check whether the first two characters and last two characters of a given string are same

PHP Basic Algorithm: Exercise-80 with Solution

Write a PHP program to check whether the first two characters and last two characters of a given string are same.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that checks if the first two characters of a string
// are equal to the last two characters of the same string
function test($s1)
{ 
    // Use substr to extract the first two characters of $s1
    $firstTwo = substr($s1, 0, 2);
    
    // Use substr to extract the last two characters of $s1
    $lastTwo = substr($s1, strlen($s1) - 2, 2);
    
    // Check if the first two characters are equal to the last two characters
    return $firstTwo == $lastTwo;
}

// Test the 'test' function with different strings, then display the results using var_dump
var_dump(test("abab"));
var_dump(test("abcdef"));
var_dump(test("xyzsderxy"));
?>

Sample Output:

bool(true)
bool(false)
bool(true)

Flowchart:

Flowchart: Check whether the first two characters and last two characters of a given string are same.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to check if a given string begins with 'abc' or 'xyz'. If the string begins with 'abc' or 'xyz' return 'abc' or 'xyz' otherwise return the empty string.
Next: Write a PHP program to concat two given strings. If the given strings have different length remove the characters from the longer 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.