How to Use PHP’s is_string() to Validate Variables – Code Examples
This guide explains PHP’s is_string() function, its syntax, and how it returns true for string variables and false otherwise, illustrated with sample code that checks name, age, and city variables, and includes best practices for input validation to avoid security risks.
In PHP, the is_string() function is a handy built‑in that checks whether a given variable is of type string, returning true if it is and false otherwise.
Function syntax
The syntax is straightforward: it accepts a single argument – the variable to be examined – and yields a boolean result.
<?php
$name = "John Doe";
$age = 25;
$city = "New York";
if (is_string($name)) {
echo "变量name是字符串类型<br>";
}
if (is_string($age)) {
echo "变量age是字符串类型<br>";
} else {
echo "变量age不是字符串类型<br>";
}
if (is_string($city)) {
echo "变量city是字符串类型<br>";
}
?>Explanation of the example
The script defines three variables: $name (a string), $age (an integer), and $city (a string). Each if statement calls is_string() on one variable.
For $name, is_string($name) returns true, so the message "变量name是字符串类型" is printed.
For $age, the function returns false, triggering the else branch that prints "变量age不是字符串类型".
For $city, the function again returns true, resulting in the output "变量city是字符串类型".
Practical considerations
When variables originate from user input, it is essential to validate the data before calling is_string() to mitigate potential security risks such as injection attacks.
Conclusion
The is_string() function provides a reliable way to confirm a variable’s type, helping developers write safer and more accurate PHP code, especially in scenarios involving user‑provided data.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
