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?