Check if all values in array are the same

In PHP, you can use the array_unique function to check if all values in an array are the same. The function returns an array with all duplicate values removed, so if the length of the returned array is equal to 1, then all values in the original array are the same. Here is an example:

<?php

$arr = [1, 1, 1, 1];
if (count(array_unique($arr)) === 1) {
  echo "All values are the same";
} else {
  echo "Values are not the same";
}

In this example, the output will be "All values are the same" because all values in the array are 1.

Watch a course Learn object oriented PHP

Another approach would be to compare the first element in the array with all other elements in the array using a for loop and return true if all element are same otherwise false.

<?php

$arr = [1, 1, 1, 1];
$first = $arr[0];
$same = true;
for ($i = 1; $i < count($arr); $i++) {
  if ($arr[$i] !== $first) {
    $same = false;
    break;
  }
}
if ($same) {
  echo "All values are the same";
} else {
  echo "Values are not the same";
}

This will also give the same output as above example.