How to Get First Character from String in PHP?

By Hardik Savani May 14, 2024 Category : PHP

Hi Folks,

In this quick example, let's see php get first character from string. In this article, we will implement a how to get first character from string in php. If you have a question about php get first character from string example then I will give a simple example with a solution. I explained simply step by step get first character from string php.

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

Example 1: 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

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 and Last Character from String

index.php

<?php

/* Declare string variable */

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

/* get First and Last Character of string */

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

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

/* Echo resulted string */

echo $first;

echo $last;

?>

Output:

W

!

I hope it can help you...

Tags :
Shares