What is PHP?
PHP is an open-source scripting language used for web development that can be embedded in HTML code. PHP is recognized for its flexibility and sizable developer community. PHP can run on many operating systems, including Windows, Linux, and macOS, and supports multiple databases such as MySQL, PostgreSQL, and SQLite.
What is a string in PHP?
A PHP string consists of character sequences, where each character is represented by one byte. Since a byte can only introduce 256 characters, the Unicode strings cannot be supported natively in PHP. When creating a string in PHP, you can use single quotes ('...'), double-quoted strings ("..."), and Heredoc syntax (<<<). PHP provides many built-in functions for replacing, splitting, concatenating, interpolating, and comparing strings. You can also convert string to lowercase, convert string to int, convert string to array, and find the length of a string.
How to find the length of a PHP string?
To find the length of a PHP string, you can use the built-in strlen() function. The following is the syntax of the strlen() function:
Where:
- $string (required): the string whose length you want to return.
How to get the number of visible characters in a PHP string?
If your string contains Unicode characters, then the strlen() function will return a string longer than the number of visible characters because the strlen() function returns the number of bytes, not characters, in the string. You can use the mb_strlen() function to get the number of visible characters. The following is the syntax of the mb_strlen() function:
Where:
- $string (required): the string whose length you want to return;
- utf8 (optional): the parameter is a character encoding. If it is omitted or null, the internal character encoding value will be used.
PHP String Length Examples
The following are examples of getting the length of a string in PHP:
Getting the length of a string
Below is an example of getting the length of a string in PHP using the strlen() function:
Getting the length of a multibyte string
Below is an example of getting the length of a multibyte string in PHP: