3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【PHP】多次元配列の孫要素の数のみをカウントしたい

Last updated at Posted at 2020-11-07

どういうことか

$array = [
  "a" => ["A", "B"]
  "b" => ["C", "D"]
]

これの大文字のアルファベットの数のみがほしい。つまり4という結果がほしい。

どうするか

結論から言うと関数一発では出せない

count関数を使う

count($array); 

// 結果 2

子要素の数しかカウントしてくれない。
したがって $array['a']$array['b'] で合計は2

COUNT_RECURSIVEを使う

count関数の第2引数にCOUNT_RECURSIVEを渡す。

count($array, COUNT_RECURSIVE);

// 結果 6 

孫要素をカウントはしてくれるが子要素もカウントしてしまう。

なんとかする

たとえば

count($array, COUNT_RECURSIVE) - count($array);

// 結果 4

とか

$count = 0;

foreach($array as $values) {
  $count += count($values);
}

// 結果 4

とか。
先輩エンジニアいわく

任意の構造があり得る中で孫要素だけ取り出すようなオプション作る意味があんまりない……

らしい。

3
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?