Jump to content

Recommended Posts

Hi guys,

 

What is "the best" way to compare the different (integer) values in an array?

Is there a function for this available or am i supposed to program it myself with for loops?

 

I found the array unique function which would remove duplicate values. Is it better to do this and check the length of the array?

 

Or is there another and better solution?

 

Link to comment
https://forums.phpfreaks.com/topic/121404-solved-compare-values-in-an-array/
Share on other sites

dunno if there's a built in function for that (would like to know myself :P) but I think you're wanting something like this?

 

<?php
// example array
$list = array('a','b','c','d','e');

$c = count($list);
for ($x = 0; $x < $c; $x++) {
   for($y = $x + 1; $y < $c; $y++) {
      if ($list[$x] == $list[$y]) {
         $duplicate = true;
      } // end if $x == $y
   } // end for $y
} // end for $x
?>

It depends.  Are you wanting to somehow preserve which 2 values are duplicate, as far as error message? Go with mine.  If you are simply wanting to display a generic "duplicate items not allowed" message, and your script doesn't need to preserve it? Go with guiltygear's.  I would have suggested what he did in the first place, but I guess I just assumed you wanted to somehow preserve it.

if you decide you want to make it a dynamic length (and thus checking against count() becomes less handy), look into using array_count_values():

 

http://us3.php.net/manual/en/function.array-count-values.php

 

combined with either a sort or a difference (i used difference), you can extract every value that was a duplicate:

 

<?php

$original = array(1, 0, 3, 3, 5, 7);

$value_counts = array_count_values($original);
$duplicates = array_keys(array_diff($value_counts, array(0)));

print_r($duplicates);

?>

 

the code's untested, but i think you'll find the difference and intersection functions for arrays is extremely handy for extracting any info you could ever want about an array.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.