Check if String Starts With a Specific Character in PHP

This tutorial will discuss about unique ways to check if string starts with a specific character in php.

Table Of Contents

Method 1: Using substr() function

Using the substr() function in PHP, we can fetch a substring from the given string.

If we pass the offset position 0 and the length of the substring as 1 in the substr() function, then it will return the first character of the string, Rhen we can compare it with the given character, if it matches, then it means that the string starts with the given character.

Let’s see the complete example,

<?php
/**
 * Checks if a string starts with a specific character
 * using the substr() function.
 *
 * @param string $str The string to check.
 * @param string $char The character to check for at the beginning of the string.
 * @return bool True if the string starts with the character, false otherwise.
 */
function startsWithChar($str, $char)
{
    return substr($str, 0, 1) === $char;
}

$strValue = "Last Coder";
$char = "L";

if (startsWithChar($strValue, $char)) {
    echo "The string starts with a specific character.";
} else {
    echo "The string does not start with a specific character.";
}
?>

Output

The string starts with a specific character.

Method 2: Using Comparision Operator

We can fetch the first character of string using the subscript operator i.e. by using the index position 0 i.e. $str[0]. It will return the first character of the string, then we can compare it with the given character. If both are equal, then it means that the string starts with a given character. But before that we also need to check if the length of the string is more than zero.

Let’s see the complete example,

<?php
/**
 * Checks if a string starts with a specific character
 * using the comparison operator.
 *
 * @param string $str The string to check.
 * @param string $char The character to check for at the beginning of the string.
 * @return bool True, If the string starts with the character, false otherwise.
 */
function startsWithCharacter($str, $char)
{
    return strlen($str) > 0 && $str[0] === $char;
}

$strValue = "Last Coder";
$char = "L";

if (startsWithCharacter($strValue, $char)) {
    echo "The string starts with a speciific character.";
} else {
    echo "The string does not start with a specific character.";
}
?>

Output

The string starts with a speciific character.

Summary

Today, we learned about two different ways to check if string starts with a specific character in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top