I'm trying to achieve to check if my array has duplicate items. But in my special case i need to use two dimensional array.
For an array that has 10 items, i managed to build this code, and i am storing values that i need to validate if they have a duplicate value or not is: $array[0][0], $array[1][0], $array[2][0]...
$arrayItemCount = 10; //means $array[0][0] to $array[9][0]
for ($p=0;$p<$arrayItemCount;$p++){
for ($h=0;$h<$arrayItemCount;$h++){
if ($array[$p][0]==$array[$h][0]){
$duplicate++;
}
}
}
I am not an expert when it comes to arrays, so any help would be appreciated.
Expected result:
$array[0][0] = 5;
$array[1][0] = 99;
$array[2][0] = 5;
echo $duplicate; //1 or true
A recursive function can be used to find duplicate values regardless of the number of dimensions.
function hasDuplicates(array $array, array &$values = []): bool
{
foreach ($array as $value) {
if (is_array($value)) {
if (hasDuplicates($value, $values)) return true;
} else {
if (isset($values[$value])) return true;
$values[$value] = 1;
}
}
return false;
}
In this example, $values is a reference to an array that keeps track of all the numbers that have been evaluated so far. Any time a non-array value is encountered, the function will try to find it in $values. If it's found, the function will immediately return true (and recursively return true to the outermost function call).
If the entire array is traversed without finding a duplicate, it will return false.
$hasDuplicates = hasDuplicates($your_array);