How can an array be checked for two identical elements in PHP?
To check for two identical elements in an array in PHP, you can iterate through the array and compare each element with every other element to find duplicates. One approach is to use nested loops to compare each element with all other elements in the array. If two elements are found to be identical, you can return true indicating the presence of duplicates.
function hasDuplicates($arr) {
$length = count($arr);
for ($i = 0; $i < $length; $i++) {
for ($j = $i + 1; $j < $length; $j++) {
if ($arr[$i] == $arr[$j]) {
return true;
}
}
}
return false;
}
// Example usage
$array1 = [1, 2, 3, 4, 2, 5];
$array2 = [1, 2, 3, 4, 5];
echo hasDuplicates($array1) ? 'Array has duplicates' : 'No duplicates found';
echo "\n";
echo hasDuplicates($array2) ? 'Array has duplicates' : 'No duplicates found';