php

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)
 

While in Java a string can also be NULL, this is not possible in PHP. If is_string() returns true, you can be sure that the variable is not NULL.
PHP MCQ - Multiple Choice Questions and AnswersPHP Questions and Answers – Object-Oriented OOP – Part 1This collection of PHP Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Object-Oriented OOP”.   1. The concept of…Read More
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.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *