How to check if PHP array is associative or sequential?

To check if an array is associative or sequential in PHP, you can use the array_keys() function and compare the resulting array of keys with the original array.

If the keys of the array are a continuous sequence of integers starting from 0, then the array is sequential. Otherwise, it is associative.

Here is an example of how you can check if an array is associative or sequential:

<?php

$array = ['a' => 1, 'b' => 2, 'c' => 3];

$keys = array_keys($array);

if ($keys !== array_keys($keys)) {
  // associative array
  echo 'associative array';
} else {
  // sequential array
  echo 'sequential array';
}

Watch a course Learn object oriented PHP

Alternatively, you can use the is_int() function to check if the keys of the array are integers:

<?php

$array = ['a' => 1, 'b' => 2, 'c' => 3];

$associative = false;

foreach ($array as $key => $value) {
  if (!is_int($key)) {
    $associative = true;
    break;
  }
}

if ($associative) {
  // associative array
  echo 'associative array';
} else {
  // sequential array
  echo 'sequential array';
}