Custom Logic to Get Unique Array Elements in php
In this post we will learn about extract function with example, how to extract unique values from an array without using PHP’s built-in array functions like array_unique or similar.
Example:
<?php
// Sample input array
$inputArray = [1, 2, 3, 2, 4, 3, 5, 6, 5];
// Function to extract unique values
function getUniqueValues($array) {
$uniqueArray = [];
foreach ($array as $value) {
// Add value to unique array if it's not already present
$isDuplicate = false;
foreach ($uniqueArray as $uniqueValue) {
if ($uniqueValue === $value) {
$isDuplicate = true;
break;
}
}
if (!$isDuplicate) {
$uniqueArray[] = $value;
}
}
return $uniqueArray;
}
// Call the function
$uniqueValues = getUniqueValues($inputArray);
// Display the unique values
echo "Unique Values: " . implode(", ", $uniqueValues);
?>
Output:
Unique Values: 1, 2, 3, 4, 5, 6
Above approach uses a nested loop to compare each value in the array with the values already added to the $uniqueArray. If the value doesn’t exist in the $uniqueArray, it gets added.
Keep Learning 🙂