Master PHP’s is_string(): Quick Guide with Real Code Examples

Learn how PHP’s is_string() function checks whether a variable is a string, understand its syntax, and see practical code examples that demonstrate handling string and non‑string variables, along with security tips for validating user input.

php Courses
php Courses
php Courses
Master PHP’s is_string(): Quick Guide with Real Code Examples

In PHP, the is_string() function is a useful tool for checking whether a variable is a string. It takes a single argument—the variable to test—and returns a boolean true if the variable is a string, otherwise false.

The syntax is simple: is_string($variable).

Below is a complete example demonstrating how to use is_string() with three different variables:

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

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

In the second if statement, is_string($age) returns false because $age is an integer, triggering the else branch that prints "变量age不是字符串类型".

The third if statement checks $city, which is also a string, so is_string($city) returns true and prints "变量city是字符串类型".

This function is valuable for validating user input, handling string‑related operations, and improving code safety and accuracy. When variables originate from user input, always perform additional validation before using is_string() to avoid potential security risks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendCode Exampletype checkingis_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

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.