How to determine the length of a string in php? The first thing many people think of is strlen() mb_strlen() functions. But in terms of program performance, these two functions are not optimal in the process of determining string length, although they are professional-level functions for detecting string length.
Through my own practice, PHP determines the length of a string. Using isset() is faster than strlen() and has higher execution efficiency.
So why is isset() faster than strlen()?
The strlen() function executes quite quickly because it does not do any calculations and just returns the known string length stored in the zval structure (C's built-in data structure used to store PHP variables). However, since strlen() is a function, it will be somewhat slow, because the function call will go through many steps, such as lowercase letters and hash search, and will be executed together with the called function. Therefore, in some cases, reasonable use of isset() can speed up your program. Because isset() is a language construct, its execution does not require function lookup and letter lowercase, etc.
Specific examples of determining the string length through isset() and strlen() are as follows:
$str='http://www.phpernote.com/php-template/436.html'; if(strlen($str)<5){echo "未满5";} if(!isset($str{5})){echo "未满5";}
Let’s analyze the two functions strlen() and isset() in detail.
PHP strlen() function
Definition and usage
strlen() function returns the length of the string.
Syntax: strlen(string)
Parameter: string
Description: Required. Specifies the string to check.
strlen() function instance
<?php echo strlen("Hello world!"); ?>
The result will be output:
12
PHP isset() function
isset function is to detect whether the variable is set.
Syntax: bool isset ( mixed var [, mixed var [, ...]] )
Return value:
If the variable does not exist, return FALSE
If the variable exists and its value is NULL, it also returns FALSE
If the variable exists and the value is not NULL, return TRUE
When checking multiple variables at the same time, TRUE will be returned only when each single item meets the previous requirement, otherwise the result will be FALSE
If a variable has been freed using unset(), it will no longer be isset(). If you use isset() to test a variable that is set to NULL, it will return FALSE. Also note that a NULL byte ("") is not equivalent to PHP's NULL constant.
Warning: isset() can only be used with variables, as passing any other parameters will cause a parsing error. If you want to check whether a constant has been set, use the defined() function.