Share via:

PHP: Check if Variable is a String

How to check if a variable is of the string type in PHP.

29 views

Edited: 2020-01-05 02:29

To check if a variable is a string, we can use the is_string function. This is also a useful way to validate the type of a input variable or function argument.

When using is_string(); in a function to validate a parameter, we can do like this:

function ($input_string) {
  if (!is_string($input_string)) {
    echo 'Invalid input. Only string types is allowed!';
    exit();
  }

  // Return the string if valid
  return 'Success: <pre>'.$input_string.'</pre> was valid.';
}

Rather than manually validating data types, we can also rely on type hinting in PHP 7. To do so we simply "hint" the type of the function or method argument:

function (string $input_string) {
  return 'Success: <pre>'.$input_string.'</pre> was valid.';
}

If the input was not valid, an E_ERROR "Uncaught TypeError" will be thrown, without you having to do any validation yourself.

If you feed the function a integer instead of string, PHP will not output any error. This is due to PHPs automatic type juggling, which considers '500' to be the same as 500. In most cases, this should not cause any problems. If you want to enable strict type checking, you can fix it by including the following at the top of your index.php:

<?php declare(strict_types=1);

Comments