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

Explanation:

  • Function Definition:
    • The function test is defined with one parameter:
      • $s1: the input string to check.
    • Extract First Two Characters:
      • The first two characters of the string $s1 are extracted using substr:
        • $firstTwo = substr($s1, 0, 2);
    • Extract Last Two Characters:
      • The last two characters of the string $s1 are extracted using substr:
        • $lastTwo = substr($s1, strlen($s1) - 2, 2);
    • Comparison:
      • The function checks if the first two characters ($firstTwo) are equal to the last two characters ($lastTwo):
        • return $firstTwo == $lastTwo;
      • It returns true if they are equal, otherwise it returns false.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-80.php