How to check if a variable is a String in PHP?
Which methods are available in PHP to check if a variable is a String? In this tutorial, we are going to see how to check if a variable is a String in PHP.
is_string()
The function is_string($var) returns whether the passed variable is a String or not:
<?php var_dump( is_string('hello') ); // true var_dump( is_string('') ); // true var_dump( is_string('5') ); // true var_dump( is_string('false') ); // true var_dump( is_string(0) ); // false var_dump( is_string(1) ); // false var_dump( is_string(5.0) ); // false var_dump( is_string(true) ); // false var_dump( is_string(new stdClass()) ); // false class Test { public function __toString() { return 'Test'; } } $obj = new Test(); var_dump( is_string($obj) ); // false var_dump( is_string((string)$obj) ); // true var_dump( is_string($obj->__toString()) ); // true ?>
Output:
bool(true) bool(true) bool(true) bool(true) bool(false) bool(false) bool(false) bool(false) bool(false) bool(false) bool(true) bool(true)
Test for float parameters
It makes sense to use is_string() to check function parameters:
<?php function startsWith($str, $start) { if (!is_string($str) || !is_string($start)) { // Error handling(Exception) throw new Exception('The parameters $str and $start must both be strings.'); } return (strpos($str, $start)===0); } try { var_dump(startsWith('StackHowTo', 'Stack')); // true var_dump(startsWith('Hello', 'llo')); // false var_dump(startsWith('100', 1)); // Exception } catch (Exception $e) { echo($e->getMessage()); } ?>
Output:
bool(true) bool(false) The parameters $str and $start must both be strings.