W3docs

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.

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:

Example of using the array_unique function to check if all values in an array are the same in PHP

<?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.

Another approach is to compare the first element with all others using a for loop, returning true if all elements are the same, otherwise false.

Example of using a for loop to check if all values in an array are the same in PHP

<?php

$arr = [1, 1, 1, 1];
if (empty($arr)) {
  echo "Array is empty";
} else {
  $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.