Detailed explanation of the steps to obtain repeated data in an array in PHP

php中世界最好的语言
Release: 2023-03-27 07:36:01
Original
3149 people have browsed it

This time I will bring you a detailed explanation of the steps to obtain duplicate data in an array in PHP. What are the precautions for obtaining duplicate data in an array in PHP? Here are practical cases, let's take a look.

Requires finding duplicate data in PHP arrays, and summarizes two methods.

1, use the functions provided by php,

array_unique and array_diff_assoc to achieve this.

<?php 
function FetchRepeatMemberInArray($array) { 
    // 获取去掉重复数据的数组 
    $unique_arr = array_unique ( $array ); 
        // 获取重复数据的数组 
    $repeat_arr = array_diff_assoc ( $array, $unique_arr ); 
    return $repeat_arr; 
}

// 测试用例 
$array = array ( 
        &#39;apple&#39;, 
        &#39;iphone&#39;, 
        &#39;miui&#39;, 
        &#39;apple&#39;, 
        &#39;orange&#39;, 
        &#39;orange&#39;  
);  www.jbxue.com
$repeat_arr = FetchRepeatMemberInArray ( $array ); 
print_r ( $repeat_arr ); 
?>
Copy after login

2,

Custom function realize this function, using two for loops

<?php 
function FetchRepeatMemberInArray($array) { 
    $len = count ( $array ); 
    for($i = 0; $i < $len; $i ++) { 
        for($j = $i + 1; $j < $len; $j ++) { 
            if ($array [$i] == $array [$j]) { 
                            $repeat_arr [] = $array [$i]; 
                break; 
            } 
        } 
    } 
    return $repeat_arr; 
}
// 测试用例 
$array = array ( 
        &#39;apple&#39;, 
        &#39;iphone&#39;, 
        &#39;miui&#39;, 
        &#39;apple&#39;, 
        &#39;orange&#39;, 
        &#39;orange&#39;  
); 
$repeat_arr = FetchRepeatMemberInArray ( $array ); 
print_r ( $repeat_arr ); 
?>
Copy after login

I believe you have mastered the method after reading the case in this article , for more exciting content, 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

php array function shuffle() and Detailed explanation of the steps to use the array_rand() random function

The array_search() function returns the key name by element value. Detailed explanation of the steps

The above is the detailed content of Detailed explanation of the steps to obtain repeated data in an array in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template