Next, let's explore a more complex optimization example with a function that checks for duplicate numbers in an array. Here's the initial version of such a function, which uses two for loops:
<?php
function containsDuplicate($array) {
for ($i = 0; $i < count($array); $i++) {
for ($j = $i + 1; $j < count($array); $j++) {
if ($array[$i] === $array[$j]) {
return true;
}
}
}
return false;
}
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1];
$result = containsDuplicate($array);
echo "Contains Duplicate: " . ($result ? "Yes" : "No");
?>
This function checks every pair of numbers, resulting in a time complexity of O(n2). Here's why: For every element in the array, it compares it with almost every other element. So, the number of operations grows quadratically with n, hence the complexity O(n2).
However, we can optimize this function by sorting the array first and then checking the elements next to each other:
<?php
function containsDuplicate($array) {
sort($array);
for ($i = 1; $i < count($array); $i++) {
if ($array[$i] === $array[$i - 1]) {
return true;
}
}
return false;
}
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1];
$result = containsDuplicate($array);
echo "Contains Duplicate: " . ($result ? "Yes" : "No");
?>
Now, even including the time it takes to sort the array (usually O(nlogn)), this updated function is more efficient. The time complexity of the sorting operation using PHP’s standard sorting algorithm is O(nlogn). After sorting, we only make a single pass through the array — an O(n) operation. But since O(nlogn) is more significant than O(n) for large n, the overall time complexity is O(nlogn).