What is the is_string method in PHP?

The is_string method can be used to check if the type of the variable is string or not.

Syntax

is_string(mixed $value): bool

This method returns true if the passed value is an string. Otherwise, it returns false.

Code

<?php
$test = 'str';
printIsString($test);
$test = '';
printIsString($test);
$test = true;
printIsString($test);
$test = 10;
printIsString($test);
function printIsString($test){
echo "The Value is: ";
var_dump($test);
echo "Is String: ";
var_dump(is_string($test));
echo "---------\n\n";
}
?>

Explanation

In the above code:

  • We used the is_string method to check if a variable is a string or not.

  • For the value str and "", the is_string method returns true.

  • But for the value true(boolean) and 10(int), the is_string method returns false because it is not a string type variable.

Free Resources