Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check whether an array is associative or a list

Short answer

array_is_list() returns true if the keys run consecutively from zero:

<?php
 
var_dump(array_is_list(['a', 'b']));
var_dump(array_is_list(['name' => 'Anna']));

Output:

bool(true)
bool(false)

A list with a gap

After unset() the keys are no longer consecutive, and the array stops being a list:

<?php
 
$items = ['a', 'b', 'c'];
unset($items[1]);
 
var_dump(array_is_list($items));
var_dump(array_is_list(array_values($items)));

Output:

bool(false)
bool(true)

Why it matters

The result of json_encode() depends on it: a list becomes an array […], and anything else an object {…}.

<?php
 
echo json_encode(['a', 'b']), ' ', json_encode([1 => 'a', 2 => 'b']);

Output:

["a","b"] {"1":"a","2":"b"}

Functions used in this recipe

  • array_is_list — Checks that the keys of an array run in order from zero.
  • array_keys — Returns all the keys of an array.
  • is_array — Checks whether a value is an array.

Thanks for reading!

Donate to the site — we work hard for you.