Home >Backend Development >PHP Problem >How to determine whether a string is repeated in php
Judgment steps: 1. Use str_split() to convert the string into a character array, the syntax "str_split (string)"; 2. Use array_unique() to remove duplicate values in the character array, the syntax "array_unique( Character array)" will return a deduplication array; 3. Use count() to obtain the length of the character array and the deduplication array; 4. Determine whether the lengths of the two arrays are equal, the syntax is "Character array length == deduplication array length" , if equal, the strings are not repeated.
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
In php, you can use arrays To determine whether the string is repeated.
Judgment steps:
Step 1. Use the str_split() function to convert the string into a character array
## The #str_split() function splits a string into characters, and these characters form an array.<?php header('content-type:text/html;charset=utf-8'); $str="Helloele"; var_dump($str); $arr=str_split($str); var_dump($arr); ?>
Step 2: Use array_unique() to remove duplicate values in the character array and return the deduplicated array
array_unique () function is used to remove duplicate values from an array. If two or more array values are the same, only the first value is retained and the other values are removed.$res=array_unique($arr); var_dump($res);
Step 3: Use the count() function to get the length of the character array and deduplication array
The count() function can Count the number of all elements in the array, that is, get the array length.$len1=count($arr); $len2=count($res);
Step 4: Determine whether the lengths of the two arrays are equal
$len1==$len2
Complete code:
<?php header('content-type:text/html;charset=utf-8'); $str="Helloele"; var_dump($str); $arr=str_split($str); var_dump($arr); $res=array_unique($arr); var_dump($res); $len1=count($arr); $len2=count($res); if($len1==$len2){ echo "字符串不重复"; }else{ echo "字符串有重复"; } ?>
## Recommended learning: "
PHP Video TutorialThe above is the detailed content of How to determine whether a string is repeated in php. For more information, please follow other related articles on the PHP Chinese website!