PHP: Get the first character in a string.

This is a short guide on how to get the first character of a string in PHP. As an added bonus, I will also show you how to get the first two characters of a string.

A simple code snippet:

<?php

//Example string.
$string = "My milkshake brings all the boys to the yard";

//Get the first character.
$firstCharacter = $string[0];

//Get the first character using substr.
$firstCharacter = substr($string, 0, 1);

//Get the first two characters using the "index" approach.
$firstTwoCharacters = $string[0] . $string[1];

//Get the first two characters using substr.
$firstTwoCharacters = substr($string, 0, 2);

We used two different approaches here.

Using the first approach, we treat the string like an array. i.e. We use the index position of the character to access it. This is possible because strings in PHP can be treated like character arrays (basically, a string is just an array that consists of characters).

In the second approach, we used the PHP function substr, which returns a part of a string. With the substr function, there are three parameters:

  1. The string in question.
  2. The index to start at (we set this to 0 because we want to start at the very beginning of the string).
  3. The length that we want to return (we set this to 1 because we only want the first character).

mb_substr and special characters.

If there is a chance that your string contains special characters such as “ö” or “ë”, then you will need to use the mb_substr function. This function is the multi-byte safe version of substr. If you use the substr on a string that contains special characters, then you might end up with jumbled characters and / or the black diamond question mark “replacement character”.

Example of mb_substr being used to get the first character of a string that contains special characters:

//Set the header to utf-8 for example purposes.
header('Content-Type: text/html; charset=utf-8');

//Example string.
$string = 'öëBC';

//Use mb_substr to get the first character.
$firstChar = mb_substr($string, 0, 1, "UTF-8");

//Print out the first character.
echo $firstChar;

Note that this function allows you to specify the encoding as a fourth parameter!

Anyway; hopefully you found this short tutorial helpful!