0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHP count()関数:配列の長さ(array length)を確認する方法

0
Posted at

😄この投稿は、codingeverybody.jpのコンテンツをもとに作成しています。

(PHPバージョン | 4+)

定義と使い方

count()関数は、指定した配列の要素数を数えて(count)、整数で返します。この関数は、配列だけでなく、Countableインターフェースを実装したオブジェクトの要素数も数えて整数で返します。

基本例

/* 一般的な数値インデックス配列 */
$array_1 = [1, 2, 3, 4, 5];
var_dump(count($array_1)); // int(5)

$array_2 = [];
var_dump(count($array_2)); // int(0)

$array_2[0] = 1;
$array_2[1] = 2;
var_dump(count($array_2)); // int(2)

/* 連想配列 */
$associative_array = [
	'name' => '山田太郎',
	'age' => 30,
	'city' => '東京'
];
var_dump(count($associative_array)); // int(3)

/* 多次元配列 */
$multi_dimensional_array = [
	[1, 2, 3],
	[4, 5, 6],
	[7, 8, 9]
];
var_dump(count($multi_dimensional_array)); // int(3)

// 多次元配列のすべての子配列の要素を含めた数を返す
var_dump(count($multi_dimensional_array, 1)); // int(12)

構文

count(Countable|array $value, int $mode = COUNT_NORMAL): int

戻り値

要素数を整数で返します。

# 多次元配列の要素数の数え方を設定

配列の中に子配列を含む多次元配列(multidimensional array)は、配列の要素として配列が存在し、その配列の中にも要素が含まれる構造です。要素数を数える際に、内部配列の要素もすべて含めた総要素数を数えたい場合は、count()関数の第2引数にCOUNT_RECURSIVEまたは1を指定します。
このように設定すると、count()関数は多次元配列のすべての要素を再帰的にたどり、内部配列の要素も含めた総要素数を返します。

$multi_dimensional_array = [
	[1, 2, 3],
	[4, 5, 6],
	[7, 8, 9]
];
var_dump(count($multi_dimensional_array)); // int(3)

// 多次元配列のすべての配列要素の数を数える
var_dump(count($multi_dimensional_array, 1)); // int(12)

Countableインターフェースを実装したオブジェクトの要素数を数える

class String_Length_Counter implements Countable {
    private $string;

    public function __construct(string $string) {
        $this->string = $string;
    }

    public function get_string_length(): int {
        return strlen($this->string);
    }

    // Countableインターフェースのメソッドを実装
    public function count(): int {
        return $this->get_string_length();
    }
}

// String_Length_Counterオブジェクトを作成
$counter = new String_Length_Counter("Hello, world!");

// count()関数を使用してオブジェクトの要素数を数える
echo "文字列の長さ: " . count($counter); // 出力: 13

この例では、String_Length_CounterクラスがCountableインターフェースを実装し、count()メソッドを定義しています。このメソッドは、文字列の長さを返すget_string_length()メソッドを呼び出してその値を返します。そして、count()関数を使用してString_Length_Counterオブジェクトの要素数を数えています。

参考資料

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?