w3resource

PHP Exercises: Create a new string of the first half of a given string of even length


63. First Half of Even-Length String

Write a PHP program to create a new string of the first half of a given string of even length.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that extracts the first half of a string
function test($s1)
{
    // Use substr to extract the substring from the beginning to the middle of s1
    return substr($s1, 0, strlen($s1) / 2);
}

// Test the 'test' function with different input strings and display the results
echo test("Hello")."\n";
echo test("Hi")."\n";
?>

Explanation:

  • Function Definition:
    • The function test is defined to take one parameter, $s1, which is expected to be a string.
  • Extract First Half of String:
    • The function calculates half the length of $s1 using strlen($s1) / 2.
    • It then uses substr($s1, 0, strlen($s1) / 2) to extract the substring from the beginning to the midpoint of $s1.
  • Return:
    • The function returns this substring, representing the first half of the original string.

Output:

He
H

Flowchart:

Flowchart: Create a new string of the first half of a given string of even length.

For more Practice: Solve these Related Problems:

  • Write a PHP script to create a new string consisting of the first half of an even-length input string.
  • Write a PHP function to slice an even-length string at its midpoint and return the left half.
  • Write a PHP program to validate that a string's length is even and then extract the first half as output.
  • Write a PHP script to compute the midpoint index and use substr to retrieve the leading segment of the string.

Go to:


PREV : First Two Characters Extraction.
NEXT : Remove First and Last Character.

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.



Follow us on Facebook and Twitter for latest update.