PHP Exercises: Check whether the first two characters and last two characters of a given string are same
80. First Two and Last Two Characters Equality
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:

For more Practice: Solve these Related Problems:
- Write a PHP script to compare the first two and the last two characters of a string and return true if they are identical.
- Write a PHP function to extract the starting and ending two-character sequences and compare them for equality.
- Write a PHP program to slice a string into two parts and check if the first two and last two letters are the same.
- Write a PHP script to use substr to obtain the first and last two characters and output a boolean based on their match.
Go to:
PREV : Check String Starts with 'abc' or 'xyz'.
NEXT : Concat with Removal for Different Lengths.
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.