LoginSignup
7
4

More than 3 years have passed since last update.

PHP: 配列が添字配列か連想配列かを判定する

Posted at

PHPで、配列が添字配列か連想配列を判定する関数です。

// 判定する関数
function is_sequential(array $array): bool
{
    $keys = array_keys($array);
    return $keys === array_keys($keys);
}

// 以下テストコード

// 添字配列
assert(is_sequential([]));
assert(is_sequential([1, 2, 3]));
assert(is_sequential(['a', 'b', 'c']));
assert(is_sequential([0 => 'x', 1 => 'x', 2 => 'x']));
assert(is_sequential(['0' => 'x', '1' => 'x', '2' => 'x'])); // 後述1

// 連想配列
assert(!is_sequential([1 => 'x', 2 => 'x', 3 => 'x'])); // 1始まりなので連想配列
assert(!is_sequential([0 => 'x', 2 => 'x', 4 => 'x'])); // 0始まりだけど、0,1,2と連続しているわけでないので連想配列
assert(!is_sequential(['a' => 'x', 'b' => 'x', 'c' => 'x'])); // キーが0,1,2と連続しているわけでないので連想配列

後述1

PHPの仕様上、キーが文字列でも、添字配列になる場合がある。

var_dump(['0' => 'x', '1' => 'x', '2' => 'x']);
array(3) {
  [0]=>
  string(1) "x"
  [1]=>
  string(1) "x"
  [2]=>
  string(1) "x"
}
7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4