Jump to content

array iteration/duplicaton search


Kasuke_Akira

Recommended Posts

I was curious if someone had an example of how to pull the first value out of an array ($array[0]) and compare it to every following value in the array ($array[1],[2],etc....)  Then compare the next value ($array[1]) and compare it to every following value ($array[2],[3],etc....).  The goal is to find any matches and, if so, to report that match.

 

I'm having trouble how to figure it out.

 

Someone recommended a combination of foreach() and array_search() but I didn't get it.

Link to comment
https://forums.phpfreaks.com/topic/44881-array-iterationduplicaton-search/
Share on other sites

try

<?php
$a  = array(1,2,3,2,4,1,5);

$k = count($a);

for($i=0; $i<$k-1; $i++) {
    for ($j=$i+1; $j<$k; $j++) {
        if ($a[$i] == $a[$j]) {
            echo "Duplicate value $a[$i], keys $i and $j<br>";
        }
    }
}
?> 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.