How to check if a string starts with "_" in PHP
Determining whether a string begins with an underscore is a common task when validating input, filtering arrays, or enforcing naming conventions like private properties or magic methods. In PHP, you have direct access to string characters through indexing, making this check straightforward without needing complex regex patterns for simple cases.
If you are working with a variable such as $variable = "_foo", the most efficient approach is to inspect the first character directly. You can do this by comparing the substring at index zero against the underscore character:
$variable = "_foo";
if ($variable[0] === '_') {
echo "The string starts with an underscore.";
} else {
echo "The string does not start with an underscore.";
}
This method relies on PHP's ability to treat strings as arrays of characters. When you access $variable[0], PHP returns the first byte of the string. For standard ASCII or UTF-8 single-byte characters like _, this is a reliable and performant check. It avoids the overhead of regular expression engines when a simple conditional statement suffices.
However, there are important nuances to consider regarding data types and encoding. If the value passed into your logic might be an integer (for example, if a user inputs 123), attempting to access $variable[0] will not throw an error immediately in older PHP versions, but it behaves inconsistently depending on the version and context. In modern PHP, accessing a character offset on an integer is treated as a type juggling issue; however, relying on this behavior is brittle. It is best practice to ensure your variable is strictly a string before performing character extraction:
$variable = "123";
if (is_string($variable) && isset($variable[0]) && $variable[0] === '_') {
// Handle underscore case
}
Using isset() on the offset adds a layer of safety. If the string is empty, $variable[0] returns an empty string "", which will correctly fail the comparison against '_'. This prevents false positives where an empty string might be misinterpreted if logic isn't strict enough.
Another approach involves using regular expressions with preg_match(). While regex is powerful for complex pattern matching, it introduces computational overhead compared to a direct character check. A pattern like /^_/ matches strings starting with an underscore:
if (preg_match('/^_/', $variable)) {
// Starts with underscore
}
This syntax works well if you are already using regex for other validations, but it should not be chosen solely for this specific check due to the slight performance penalty and increased complexity in reading the code.
In frameworks like Laravel, this logic often appears when filtering protected properties or validating method names. If you need to ensure a variable does not start with an underscore (as requested in the scenario), simply invert the condition:
if (!($variable[0] === '_')) {
// The string is safe to use as a public identifier
}
Be cautious about edge cases where the string might be empty. An empty string has no first character, so accessing index 0 yields an empty string, which is not equal to '_'. This naturally handles the negative case without explicit checks for length, provided you trust the input type.
Ultimately, direct indexing remains the preferred solution for this specific requirement. It is readable, fast, and leverages PHP's native string handling capabilities. Reserve regular expressions for when the pattern becomes more complex, such as checking for an underscore followed by specific alphanumeric sequences.