How to check if variable is string in PHP

779 views 7 months ago 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.

<php
$value = 'This is string';
var_dump(is_string($value)); // bool(true)

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

<?php
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.

<?php
$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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]