PHPのarray_count_values()
関数は、配列の中の、それぞれの値の、重複数を調べる組み込み関数。
定義
配列型 array_count_values( 配列型 $input );
パラメータ
- 配列型 $input
重複数を調べる対象の配列。
戻り値
「配列型 $input」の配列要素の値をキー、重複数を値とする連想配列。
構文
配列の値の重複数を調べる
重複数の配列 = array_count_values( 配列 );
「配列」の中の、値ごとの、重複数を調べる。
サンプル
配列の値の重複数を調べる
<pre>
<?php
$varArray = array( "Red", "Blue", "Green", "Blue", "Red", "Red", "Red" );
print_r( array_count_values( $varArray ) );
?>
</pre>
<?php
$varArray = array( "Red", "Blue", "Green", "Blue", "Red", "Red", "Red" );
print_r( array_count_values( $varArray ) );
?>
</pre>
↓↓↓出力結果↓↓↓
Array
(
[Red] => 4
[Blue] => 2
[Green] => 1
)
(
[Red] => 4
[Blue] => 2
[Green] => 1
)
連想配列の値の重複数を調べる
<pre>
<?php
$varArray = array(
"a" => "Red",
"b" => "Blue",
"c" => "Green",
"d" => "Blue",
"e" => "Red",
"f" => "Red",
"g" => "Red"
);
print_r( array_count_values( $varArray ) );
?>
</pre>
<?php
$varArray = array(
"a" => "Red",
"b" => "Blue",
"c" => "Green",
"d" => "Blue",
"e" => "Red",
"f" => "Red",
"g" => "Red"
);
print_r( array_count_values( $varArray ) );
?>
</pre>
↓↓↓出力結果↓↓↓
Array
(
[Red] => 4
[Blue] => 2
[Green] => 1
)
(
[Red] => 4
[Blue] => 2
[Green] => 1
)