PHP Exercises: Check if a given string ends with "on"
Write a PHP program to check if a given string ends with "on".
Sample Solution:
PHP Code :
<?php
// Define a function named 'test' that extracts the last two characters from the input string
function test($s1)
{
// Use substr to obtain the last two characters of the input string
return substr($s1, strlen($s1)-2, 2);
}
// Test the 'test' function with different strings and display the results using var_dump
var_dump(test("Hello"));
var_dump(test("Python"));
var_dump(test("on"));
var_dump(test("o"));
?>
Explanation:
- Function Definition:
- A function named test is defined with one parameter, $s1, which represents the input string.
- Extracting the Last Two Characters:
- The function uses substr($s1, strlen($s1) - 2, 2):
- strlen($s1) - 2 calculates the starting position, which is two characters from the end of the string.
- 2 specifies that two characters should be extracted from this position.
- Return Value:
- The function returns the last two characters of $s1. If $s1 has less than two characters, it returns the whole string.
Output:
string(2) "lo" string(2) "on" string(2) "on" string(1) "o"
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to create a new string using the two middle characters of a given string of even length (at least 2).
Next: Write a PHP program to create a new string using the first and last n characters from a given string of length at least n.
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