w3resource

PHP Exercises: Check if a given string ends with "on"

PHP Basic Algorithm: Exercise-71 with Solution

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

Sample Output:

string(2) "lo"
string(2) "on"
string(2) "on"
string(1) "o"

Flowchart:

Flowchart: Check if a given string ends with 'on'.

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.



Follow us on Facebook and Twitter for latest update.