Horje
Remove Duplicate Value Foreach

Removing duplicate values within a foreach loop can be achieved by maintaining a separate collection of unique elements and checking against it during iteration.


Method 1: Using a temporary array/list and array_unique (PHP example)

This approach involves collecting all items into a new array and then applying a function to remove duplicates after the loop concludes.

index.php
Example: PHP
<?php
$originalArray = ["apple", "banana", "apple", "orange", "banana"];
$tempArray = [];
foreach ($originalArray as $item) { array_push($tempArray, $item);
}
$uniqueArray = array_unique($tempArray);
foreach ($uniqueArray as $uniqueItem) { echo $uniqueItem . "<br>
";
}
?>

Output should be:





php foreach

Type:
Develop
Category:
Web Tutorial
Sub Category:
PHP String Tutorial
Uploaded by:
Admin