In this PHP tutorial, you shall learn how to delete the last character from given string using substr() function, with example programs.

PHP – Delete last character in string

To delete last character from a string in PHP, we can find the substring from starting position to last but one position of the given string.

Call substr() function and pass the given string, starting index, and last but one of the ending index of the string as arguments.

Syntax

The syntax to get the string str without its last character using substr()function is

substr($str, 0, strlen($str) - 1)

The function returns a string value.

ADVERTISEMENT

Examples

1. Remove last character of a string

In this example, we will take a string str and find an output string which is made from str but without the last character.

PHP Program

<?php
  $str = 'apple';
  $output = substr($str, 0, strlen($str) - 1);
  echo $output;
?>

Output

PHP - Delete last character of string - Example

Conclusion

In this PHP Tutorial, we learned how to delete the last character of a string, using substr() function.