Backend Development 4 min read

Using PHP is_string() to Determine Whether a Variable Is a String

This article explains the PHP is_string() function, its syntax, and provides a complete example showing how to check variables $name, $age, and $city to determine if they are strings, along with best‑practice security considerations.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP is_string() to Determine Whether a Variable Is a String

In PHP, the is_string() function is a useful built‑in function that checks whether a given variable is of type string, returning true if it is and false otherwise.

The syntax is straightforward: is_string($variable) takes a single argument—the variable to be examined—and returns a boolean result.

Below is a complete example demonstrating the function:

<?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>";
}
?>

The code defines three variables: $name , $age , and $city . The is_string() function is then used to test each variable.

In the first if statement, is_string($name) returns true because $name holds a string, so the script outputs "变量name是字符串类型".

In the second if statement, is_string($age) returns false because $age is an integer, resulting in the output "变量age不是字符串类型".

In the third if statement, is_string($city) returns true as $city is also a string, producing the message "变量city是字符串类型".

This demonstration shows how is_string() can be employed to validate variable types, which is especially useful for verifying user input and handling string‑related operations securely.

When variables originate from user input, it is important to perform additional input validation before using is_string() to mitigate potential security risks.

In summary, the is_string() function provides a simple and reliable way to check if a variable is a string, helping developers write safer and more accurate PHP code.

backendphpstring validationphp-functionsis_string
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.