How to remove duplicates elements from an array in PHP?
- Posted on December 9, 2024
- Technology
- By MmantraTech
- 45 Views

Solution : Without using pre-built method
<?php
$array = [1, 2, 2, 3, 4, 4, 5];
$unique_array = [];
foreach ($array as $value) {
if (!isset($unique[$value])) { // Check if the value is already in the unique array
$unique[$value] = $value; // Mark the value as seen
}
}
$res = array_keys($unique);
print_r($res);
?>
Solution : Using pre-built method
<?php
// Example array with duplicates
$array = [1, 2, 2, 3, 4, 4, 5];
// Remove duplicates
$uniqueArray = array_unique($array);
// Output the result
print_r($uniqueArray);
?>
Write a Response