0

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
}
}
2
  • what do you want to do with the duplicated? remove? store? count? Commented Mar 17, 2014 at 23:58
  • possible duplicate of Php check duplicate values in an array Commented Mar 18, 2014 at 0:11

3 Answers 3

0

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
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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).
0

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

2 Comments

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).
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.
0

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)) {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.