In this tutorial, you shall learn how to check if any two adjacent values are same in a given array in PHP using For loop and Equal-to operator, with the help of example programs.

PHP – Check if any two Adjacent values are same in array

To check if any two adjacent values are same in a given array in PHP, we can iterate through the elements of the array using For loop, and compare the values.

Example

In this example, we take an array arr with some elements. We check if any two subsequent values are same in this array.

PHP Program

</>
Copy
<?php
  $arr = ["apple", "banana", "fig", "fig", "cherry"];
  
  $found = false;

  for ($i = 0; $i < count($arr) - 1; $i++) {
    if ($arr[$i] == $arr[$i + 1]) {
      $found = true;
      break;
    }
  }

  if ( $found ) {
    print_r('We have found two adjacent values with same value.');
  } else {
    print_r('We have not found any two adjacent values with same value.');
  }
?>

Output

PHP - Check if any two subsequent values are same in array

Conclusion

In this PHP Tutorial, we learned how to check if any two subsequent values are same in array using For loop and equal to operator.