-3

Although I'm fairly experienced with PHP, I recently meet with this issue which driving me nuts.

    <?PHP
// This code is just basic example
$we_need = array(
    'Carrot',
    'Onion',
    'Milk',
    'Onion',
    'Potato'
); // Notice that Onion is on two places
$basket  = array(); // An empty basket
foreach ($we_need as $product) {
    // Add product to basket ONLY if it's not already there
    if (!in_array($product, $basket)) {
        $basket[] = $product;
    } else {
        echo "For debugging: Duplicate detected, so skipped.\n";
    }
}
print_r($basket);
?>

What is wrong with this code? Why $basket array have duplicates at the end?
In my real program, $we_need is fetched from database, but it isn't multidimensional array nor new lines in values.
I know that I can use array_unique() for this approach, but I want to know where the problem is?

xZero
  • 645
  • 2
  • 9
  • 24

1 Answers1

0

There is a closing bracket missing.

foreach ($we_need as $product) {

    // Add product to basket ONLY if it's not already there
    if (!in_array($product, $basket)) {
        $basket[] = $product;
    } else {
        echo "For debugging: Duplicate detected, so skipped.\n";
    } // <<<------- here
}

Then you get:

For debugging: Duplicate detected, so skipped. 
Array ( [0] => Carrot [1] => Onion [2] => Milk [3] => Potato )
Jens A. Koch
  • 39,862
  • 13
  • 113
  • 141
  • That would be the answer, if missing bracket really missing in my original code. – xZero May 22 '15 at 10:28
  • 1
    Thank you for testing it out. It seems that code works for everyone except me, so I conclude that problems must lay in PHP installation on my server. Your answer doesn't fix the issue, and it doesn't have, but will help others to see working version of the code and my comment as well, if nothing help. – xZero May 22 '15 at 10:36