39

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,989
  • 18
  • 64
  • 106

7 Answers7

75

For the single-byte encoded (binary) strings:

substr($username, 0, 1);
// or 
$username[0] ?? null;

For the multi-byte encoded strings, such as UTF-8:

mb_substr($username, 0, 1);
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
James Wallen-Jones
  • 1,008
  • 8
  • 10
  • 6
    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
18

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
  • 10,078
  • 2
  • 51
  • 58
6

In PHP 8 if you just need to check if the first character of a given string is equal to something, you can do it like this:

if (str_starts_with($s, $characterToCheck)) {
    // DO SOMETHING
}
Dawid Ohia
  • 16,129
  • 24
  • 81
  • 95
2

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

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

Strings in PHP are array like, so simply

$username[0]
mega6382
  • 9,211
  • 17
  • 48
  • 69
Szymon D
  • 441
  • 2
  • 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,819
  • 1
  • 23
  • 30
0

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

Nabil Kadimi
  • 10,078
  • 2
  • 51
  • 58
Vitor Ferreira
  • 163
  • 1
  • 3
  • 11