Ceejay
Ceejay

Reputation: 7257

How to get the first character of string in 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);
  ?>

Upvotes: 56

Views: 165142

Answers (7)

Nabil Kadimi
Nabil Kadimi

Reputation: 10384

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];

Upvotes: 29

Dawid Ohia
Dawid Ohia

Reputation: 16435

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
}

Upvotes: 8

James Wallen-Jones
James Wallen-Jones

Reputation: 1268

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);

Upvotes: 100

alexsoin
alexsoin

Reputation: 141

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

mb_substr($username, 0, 1, "UTF-8");

Upvotes: 3

Vitor Ferreira
Vitor Ferreira

Reputation: 163

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

Upvotes: 0

Szymon D
Szymon D

Reputation: 441

Strings in PHP are array like, so simply

$username[0]

Upvotes: 0

Parth Chavda
Parth Chavda

Reputation: 1829

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

Upvotes: 0

Related Questions