Home  >  Article  >  Backend Development  >  PHP determines duplicate values ​​in array

PHP determines duplicate values ​​in array

php中世界最好的语言
php中世界最好的语言Original
2018-05-21 10:43:241387browse

This time I will bring you PHP to determine repeated values ​​​​in an array. What are the precautions for PHP to determine repeated values ​​​​in an array? The following is a practical case, let's take a look.

Suppose there are several values ​​in an array $a. How to determine whether there are the same values ​​among these values?

Using
php array function array_unique, you can easily solve this problem.

array_unique(PHP 4 >= 4.0.1, PHP 5)

array_unique -- Remove duplicate values ​​from an array

Description

array array_unique ( array array )

array_unique() accepts an array as input and returns a new array without duplicate values.

Note that the key name remains unchanged. array_unique() first sorts the values ​​as
string, then retains only the first encountered key name for each value, and then ignores all subsequent key names. This does not mean that the first occurrence of the same value in an unsorted array will be preserved. Note: Two units are considered the same if and only if (
string) $elem1 === (string) $elem2. That is, when the expressions of the strings are the same. The first unit will be retained.

The following are two examples of the array_unique function for your reference.

<?php      
$input = array("a" => "green", "red", "b" => "green", "blue", "red");      
$result = array_unique($input);      
print_r($result);      
?>

Output:


Array      
(      
    [a] => green      
    [0] => red      
    [1] => blue      
)

Example 2, array_unique() and type


<?php      
$input = array(4, "4", "3", 4, 3, "3");      
$result = array_unique($input);      
var_dump($result);      
?>

Output:


array(2) {      
  [0] => int(4)      
  [2] => string(1) "3"     
}

Believe After reading the case in this article, you have mastered the method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

How to use array_sum() to calculate the sum of array element values

Summary of how to use php array search function

The above is the detailed content of PHP determines duplicate values ​​in array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn