Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first character of string in php

Tags:

php

I need to get the first character of the given string. here i have a name in the session variable. i am passing the variable value to the substr to get the first character of the string. but i couldn't.

i want to get the first character of that string.

for example John doe. i want to get the first character of the string j. how can i get it using php?

  <?php
      $username = $_SESSION['my_name'];
      $fstchar = substr($username, -1);
  ?>
like image 722
CJAY Avatar asked Nov 24 '15 10:11

CJAY


People also ask

How do you get the first character of a string in PHP?

In PHP to remove characters from beginning we can use ltrim but in that we have to define what we want to remove from a string i.e. removing characters are to be known. $str = "geeks" ; // Or we can write ltrim($str, $str[0]); $str = ltrim( $str , 'g' );

How do I find the first letter of a string?

Method 1: Using String.The charAt() method accepts a parameter as an index of the character to be returned. The first character in a string is present at index zero and the last character in a string is present at index length of string-1 .

How do I get the first letter of a variable in PHP?

You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

How can I get the first 3 characters of a string in PHP?

To get the first n characters of a string, we can use the built-in substr() function in PHP. Here is an example, that gets the first 3 characters from a following string: <? php echo substr("Google", 0, 3); ?>


2 Answers

substr($username, 0, 1);

This will get you the first character

Another way is to do this:

$username[0];
like image 52
James Wallen-Jones Avatar answered Sep 25 '22 07:09

James Wallen-Jones


Three solutions sorted by robustness

    1. mb_substr: It takes into considetation the text encoding.
      Example: mb_substr($str, 0, 1)
    1. substr
      Example: substr($str, 0, 1)
    1. Using brackets: to avoid as it throws a notice in PHP 7.x and a warning in PHP 8.x if the string is empty
      Example: $str[0]
like image 37
Nabil Kadimi Avatar answered Sep 22 '22 07:09

Nabil Kadimi