How to check if variable is string or not in PHP

PHP is simple programming method by which you can use so many in-built functions to give easy coding. In this article, I will show you how to check if given variable is string or not.

There is function is_string($value) which returns true if given variable is string.


$value = 'This is string';

var_dump(is_string($value)); // bool(true)

Here few examples of few types of data with output to check:


var_dump(is_string(false)); // bool(false)
var_dump(is_string(true)); // bool(false)
var_dump(is_string(NULL)); // bool(false)
var_dump(is_string('abc')); // bool(true)
var_dump(is_string('23')); // bool(true)
var_dump(is_string(23)); // bool(false)
var_dump(is_string('23.5')); // bool(true)
var_dump(is_string(23.5)); // bool(false)
var_dump(is_string('')); // bool(true)
var_dump(is_string(' ')); // bool(true)
var_dump(is_string('0')); // bool(true)

So, it is also better to check $val !== '' or empty($val). Let's have look below example.


$val = '';

function is_string_value($val) {
    return is_string($val) && $val !== '';

var_dump(is_string($val)); // bool(true)
var_dump(is_string_value($val)); // bool(false)

I hope you would like this article. Follow us on Twitter and like us on Facebook.