LoginSignup
4
2

More than 5 years have passed since last update.

PHPの配列のキーの型について

Last updated at Posted at 2017-01-20

配列のキーに翻弄される事があったので、備忘録です。

公式ドキュメント

  • キーの型は整数型と文字列型がある
  • 整数型のキーが10進数以外であれば、10進数に変換される
  • キャストとはロジックが異なる

キーにする値 キーの型 備考
1 整数
'1' 整数
1.2 整数 1に変換される
0332 整数 10進数の218に変換される
'1a' 文字列
'test' 文字列

例えば、DBから取得した整数文字列のPKなどをキーに指定します。
それが「先頭が0、かつ8も9も含まれていない値」の場合、8進数としてみなされます。

arraykey.php
<?php
declare(strict_types=1);

$data[0332] = "0332";
var_dump($data);

// array(1) {
//   [218] =>
//   string(4) "0332"
// }

整数型になると困る場合

  • 半角数字以外の文字列を連結する
  • キーにはハッシュ値など文字列になり得るものを用いる
4
2
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
4
2