w3resource

PHP Exercises: Create a new string of length 2 starting at the given index of a given string

PHP Basic Algorithm: Exercise-73 with Solution

Write a PHP program to create a new string of length 2 starting at the given index of a given string.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that extracts a substring of length 2 starting from the specified index in the input string
// If the index + 2 exceeds the length of the string, extract the first 2 characters
function test($s1, $index)
{ 
   // Use substr to extract a substring of length 2 starting from the specified index
   // If the index + 2 exceeds the length of the string, extract the first 2 characters
   return $index + 2 <= strlen($s1) ? substr($s1, $index, 2) : substr($s1, 0, 2);
}

// Test the 'test' function with different strings and index values, then display the results using echo
echo test("Hello", 1)."\n";
echo test("Python", 2)."\n";
echo test("on", 1)."\n";
?>

Sample Output:

el
th
on

Flowchart:

Flowchart: Create a new string of length 2 starting at the given index of a given string.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: 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.
Next: Write a PHP program to create a new string taking 3 characters from the middle of a given string at least 3.

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.