How to Get First and Last Character from String in PHP?

By Hardik Savani May 14, 2024 Category : PHP

Hello Folks,

This tutorial will provide an example of php get first and last character from string. This example will help you how to get first and last character from string in php. This example will help you php get first and last character from string example. if you want to see an example of get first and last character from string php then you are in the right place.

we will use substr() php function to get first and last character from string. i will give you very simple examples to get first and last character from string in php.

Example 1: PHP Get First and Last Character from String

index.php

<?php

/* Declare string variable */

$myString = "Welcome to ItSolutionStuff.com!";

/* get First and Last Character of string */

$last = substr($myString, 0, 1);

$last = substr($myString, -1);

/* Echo resulted string */

echo $last;

echo $last;

?>

Output:

W

!

Example 2: PHP Get Last Character from String

index.php

<?php

/* Declare string variable */

$myString = "Welcome to ItSolutionStuff.com!";

/* get Last Character of string */

$char = substr($myStr, -1);

/* Echo resulted string */

echo $char;

?>

Output:

!

Example 3: PHP Get First Character from String

index.php

<?php

/* Declare string variable */

$myString = "Welcome to ItSolutionStuff.com!";

/* get First Character of string */

$char = substr($myString, 0, 1);

/* Echo resulted string */

echo $char;

?>

Output:

W

I hope it can help you...

Tags :
Shares