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.
Frequently Asked:
- Check if String is an Integer in PHP
- Check if String is Boolean in PHP
- Check if String Contains Line Break in PHP
- Check if a String Contains Only Numbers in PHP
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.