get string length in PHP


Answers ( 1 )


    In PHP, you can get the length of a string using the strlen() function.

    Here's a brief overview and an example of how to use it:

    strlen() Function

    • Purpose: The strlen() function in PHP is used to get the length of a string.
    • Return Value: It returns the length of the string on success, and 0 if the string is empty.

    Example Usage

    $str = "Hello World!";
    echo strlen($str); // Outputs: 12

    In this example, the strlen() function is used to calculate the length of the string stored in the variable $str. The string "Hello World!" has 12 characters, including the space, so strlen($str) returns 12.


    • strlen() counts the number of bytes in the string. If you are working with multi-byte character encodings, like UTF-8, and you need to get the actual number of characters, you should use mb_strlen() instead.
    • mb_strlen() is part of the Multibyte String extension in PHP and is used for strings encoded in multi-byte encodings.

    Example of mb_strlen() Usage

    $str = "こんにちは"; // Japanese for "Hello"
    echo mb_strlen($str, "UTF-8"); // Outputs: 5

    In this example, mb_strlen() correctly counts the number of characters in a UTF-8 encoded string.

Leave an answer