How to Find Peak Element in the Array in PHP?

In an array, a peak element is an element that is greater than or equal to its neighbours. To find a peak element in an array using PHP, you can use various approaches. One simple approach is to iterate through the array and check each element to see if it is greater than or equal to its neighbours.

Here’s an example implementation in PHP:

<?php
function findPeakElementNaive($arr) {
$n = count($arr);
for ($i = 1; $i < $n - 1; $i++) {
if ($arr[$i] > $arr[$i - 1] && $arr[$i] > $arr[$i + 1]) {
return $i; // Index of the peak element
}
}
return -1; // No peak element found
}
$arr = [1, 3, 20, 4, 1, 0];
$peakIndex = findPeakElementNaive($arr);
if ($peakIndex != -1) {
echo "Peak element is: " . $arr[$peakIndex] . " at index: " . $peakIndex;
} else {
echo "No peak element found";
}
?>

This implementation checks the first and last elements separately and then iterates through the array to find a peak element. Keep in mind that this is a basic example, and there are more optimized algorithms for finding peak elements, such as binary search, which can be more efficient for larger arrays.