13

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);
  ?>
CJAY
  • 6,435
  • 17
  • 58
  • 100

7 Answers7

29
substr($username, 0, 1);

This will get you the first character

Another way is to do this:

$username[0];
  • 1
    If `$username` is an empty string, `$username[0]` produces a notice on PHP 7.x and a warning in PHP 8.x. [Example](https://3v4l.org/b00Jd) – Nabil Kadimi Sep 30 '21 at 03:32
3

Three Solutions Sorted by Robustness

1. mb_substr

It takes into consideration text encoding. Example:

$first_character = mb_substr($str, 0, 1)

2. substr

Example:

$first_character = substr($str, 0, 1);

3. Using brackets ([])

Avoid as it throws a notice in PHP 7.x and a warning in PHP 8.x if the string is empty. Example:

$first_character = $str[0];
Nabil Kadimi
  • 9,428
  • 2
  • 49
  • 56
0

Best way to do this is by doing this

$fstchar = $username[0];
Vivek Jain
  • 3,733
  • 6
  • 28
  • 46
mega6382
  • 8,889
  • 16
  • 47
  • 67
0

Strings in PHP are array like, so simply

$username[0]
mega6382
  • 8,889
  • 16
  • 47
  • 67
Szymon D
  • 323
  • 1
  • 13
0

Strings can be seen as Char Arrays, and the way to access a position of an array is to use the [] operator, so there's no problem at all in using $str[0] (and I'm pretty sure is much faster than the substr method).

$fstchar = $username[0];

faster than all method

Parth Chavda
  • 1,791
  • 1
  • 20
  • 29
0

I do not have too much experience in php, but this may help you: substr

Nabil Kadimi
  • 9,428
  • 2
  • 49
  • 56
Vitor Ferreira
  • 151
  • 1
  • 3
  • 11
0

If the problem is with the Cyrillic alphabet, then you need to use it like this:

mb_substr($username, 0, 1, "UTF-8");
alexsoin
  • 61
  • 1
  • 5