The right data type can make or break your PHP app. This is also why, now and then, you need to check if a given variable is of the right data type before you go on and do something else with it.
You’re reading this post, which means you’re wondering about the best way to check if a given variable is a string or not in PHP. Read on, and you will find the answer.
To check if a variable is a string in PHP, use the is_string() variable-handling function. It will test the data type of the variable, returning true
if it’s a string and false
if it isn’t.
The is_string() function is available out of the box, without the need to install or configure PHP extensions, and is supported in PHP 4, PHP 5, PHP 7, and PHP 8.
How It Works
You use the is_string() function by passing on the variable as a parameter. When called, the function will check whether the data type of the variable is a string or not and return a boolean: true
if it is indeed a string, and false
if it isn’t.
is_string(variable) : boolean
In terms of code, here’s how an implementation based on the is_string()
function could look like:
<?php
function test_string($my_string) {
if (is_string($my_string)) {
// Do something if true
echo "Yes, it's a string.";
}
else {
// Do something else if false
echo "No, it isn't a string.";
}
}
test_string("String to test");
?>
Play around with this function in a PHP compiler (whether on your computer or online) until you learn the ropes.
You will see that the following parameters are a string:
- test_string(“String to test”) is a string
- test_string(“42”) is a string
- test_string(“1.5”) is a string
- test_string(“”) is a string
- test_string(” “) is a string
- test_string(“0”) is a string
And the following parameters aren’t a string:
- test_string(42) isn’t a string
- test_string(1.5) isn’t a string
- test_string(0) isn’t a string
- test_string(true) isn’t a string
- test_string(false) isn’t a string
- test_string(NULL) isn’t a string
Edge Cases
As noted by a user in the PHP Manual, if you use the is_string()
function on an object, it will always return false
, even if you’ve used the __toString()
function on that object beforehand.
In Conclusion
All in all, is_string()
is a handy function to keep in your backpocket for when you want to double-check that a variable is indeed a string before doing anything else to it.