How to get the first character of string in php
A common stumbling block for developers working with session data or simple string manipulation is misunderstanding how indexing works. You might have a variable like $username pulled from $_SESSION['my_name'], and you need just the very first letter. In the snippet provided in your source material, the logic fails because of a specific off-by-one error:
<?php
$username = $_SESSION['my_name'];
$fstchar = substr($username, -1); // This gets the LAST character!
?>
The culprit is the second argument in substr(). By default, this function expects a starting position relative to the beginning of the string (0-indexed). When you pass -1, you are explicitly telling PHP to start counting from the end. Consequently, $fstchar holds the last letter of "John Doe" (e), not the first (J).
To retrieve the actual first character, you must pass 0 as the starting position. Here is the corrected implementation:
<?php
$username = $_SESSION['my_name'];
$fstchar = substr($username, 0, 1); // Start at 0, extract length of 1
?>
The second argument in substr() is optional; if omitted, the function returns the rest of the string. However, explicitly passing a length of 1 makes the intent crystal clear and prevents accidental data leakage if the first character happens to be an emoji or a multi-byte sequence that behaves unexpectedly in older PHP versions.
Handling Edge Cases
Before running this code, you need to consider what happens when the string is empty. If $username is null or an empty string "", calling substr() with a length of 1 will simply return an empty string. This usually doesn't crash the script, but it might break your downstream logic if you assume a single character always exists.
It is best practice to guard against this scenario:
<?php
$username = $_SESSION['my_name'] ?? ''; // Ensure fallback value
$fstchar = strlen($username) > 0 ? substr($username, 0, 1) : '';
?>
Alternatively, you can use the isset() function or check if the string is not empty before accessing it. This defensive coding approach prevents silent failures where your application might proceed with an empty value instead of a character.
Dealing with Multi-byte Characters (UTF-8)
If your application serves international users, the string stored in the session is likely UTF-8 encoded. In PHP versions prior to 7.2, using substr() on multi-byte strings (like those containing Chinese characters or emojis) can result in splitting a character into its constituent bytes, leading to garbled output.
For example, extracting the first character from "ð" might fail if you don't specify byte length versus character length correctly. In modern PHP environments, mb_substr() is the safer alternative for UTF-8 strings:
<?php
$username = $_SESSION['my_name'];
$fstchar = mb_substr($username, 0, 1); // Handles multi-byte characters safely
?>
Using mb_substr() ensures that you are counting Unicode scalar values rather than raw bytes. While this adds a slight overhead, it is negligible for most applications and prevents subtle bugs in globalized codebases. If your project strictly uses ASCII-only names, the standard substr() function remains perfectly efficient and readable.
Conclusion
Getting the first character of a string in PHP is a trivial task once the indexing logic is understood. The primary mistake lies in confusing negative indices (which count backward from the end) with forward indices. By setting the start position to 0 and explicitly defining the length, or by switching to mb_substr() for international support, you ensure robust and predictable behavior regardless of the input data.
