Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

The values in this array are inserted by pulling XML values (using the simplexml_load_file method) and a foreach loop.

$skuArray(2, 4, 3, 7, 7, 4, 1, 7, 9);

After populating the array, I then need to check to see if any duplicate values exist in the array (IE, 7 and 4 in this case). Product->sku contains the skuArray value (from an XML file) in the foreach loop below. The code below isn't working. Any advice? Thanks!

foreach($XMLproducts->product as $Product) {
if (in_array($Product->sku, $skuArray, > 1) {
// execute code
}
}
share|improve this question
    
what do you want to do with the duplicated? remove? store? count? –  Dagon Mar 17 at 23:58
    
possible duplicate of Php check duplicate values in an array –  MarianoCordoba Mar 18 at 0:11

3 Answers 3

Use array_count_values() to get the number of times a value occurs and then check to see if it is more than one

$skuArray = array(2, 4, 3, 7, 7, 4, 1, 7, 9);
$dupes = array_count_values($skuArray);    
foreach($XMLproducts->product as $Product) {
  if ($dupes[$Product->sku] > 1) {
    // execute code
   }
}
share|improve this answer
    
Thanks! This code should work, but for some reason it isn't. Perhaps because using the simplexml_load_file method may not be pulling a numeric value to test in the if statement (if > 1). –  Dean Olsen Mar 18 at 1:56

If you need to remove the duplicates then you can use array_unique:

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

If you need only check if there are duplicates then you can do it using array_count_values:

<?php
$input = array(2, 4, 3, 7, 7, 4, 1, 7, 9);
$counts = array_count_values($input);
$duplicates = array();
foreach($counts as $v => $count){
    if($count > 1)
        $duplicates[] = $v;
}

Then you will have an array $duplicates with the duplicated values.

Source: Php check duplicate values in an array

share|improve this answer
    
Thanks! This code should work, but for some reason it isn't. Perhaps because using the simplexml_load_file method may not be pulling a numeric value to test in the if statement (if > 1). –  Dean Olsen Mar 18 at 1:56
    
Are you sure that the format of the array is like array(2, 4, 3, 7, 7, 4, 1, 7, 9)? Here you can see this code working. –  MarianoCordoba Mar 18 at 2:27

Your code has typo:

if (in_array($Product->sku, $skuArray, > 1) {

in_array expect the first parameter the needle, but you mentioned "Product->sku contains the skuArray value ", anyway, it should be like this:

if (in_array($Product->sku, $skuArray)) {
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.