Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / PHP

Typ PHP iterable

Przyjmuje tablicę lub obiekt implementujący Traversable.

Wersja: PHP 8.4; repository runtime, production runtime not attested

Składnia

function total(iterable $values): int

Przyjmuje tablicę lub obiekt implementujący Traversable. Pętla foreach obsłuży obie postacie bez założenia, że mają rozmiar albo dostęp przez indeks. Generator może się wyczerpać. Do ponownego przejścia zapewnij nowy generator lub przechowaj wartości. Sam napis nie spełnia tego typu.

declare(strict_types=1);
function total(iterable $values): int { $n = 0; foreach ($values as $v) { $n += $v; } return $n; }
function numbers(): Generator { yield 2; yield 5; }
echo json_encode([total([2,5]), total(numbers()), is_iterable('25')]);
[7,7,false]

Przykłady

<?php
declare(strict_types=1);
function total(iterable $values): int { $n = 0; foreach ($values as $v) { $n += $v; } return $n; }
function numbers(): Generator { yield 2; yield 5; }
echo json_encode([total([2,5]), total(numbers()), is_iterable('25')]);

Wynik

[7,7,false]

Źródła