get string length in PHP


Answers ( 1 )

  1. In PHP, the length of a string can be determined using the strlen() function. This function returns the number of bytes in a string. Here's an example:

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

    This code snippet will output the length of the string stored in the variable $str, which in this case is 12 characters.

    It's important to note that strlen() counts bytes rather than characters. This distinction is particularly relevant when dealing with multibyte character encodings like UTF-8. In a UTF-8 string, a single character can use more than one byte. If you need to count the actual number of characters in a UTF-8 string, you should use the mb_strlen() function, which is part of the Multibyte String extension in PHP:

    $str = "你好世界"; // A string in Chinese
    echo mb_strlen($str, 'UTF-8');  // Outputs: 4

    This function will correctly count the number of characters in a multibyte string, given the appropriate character encoding (in this case, 'UTF-8').

Leave an answer