Skip to content

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 a re-indexed version of itself.

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:

How to check if PHP array is associative or sequential?

php
<?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';
}

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

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

How to check if PHP array is associative or sequential by using is_int() function?

php
<?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';
}

Note that in PHP, all arrays are ordered maps. The terms "sequential" and "associative" are conventions used to describe key types rather than distinct data types.

Dual-run preview — compare with live Symfony routes.