CKTIS / PHP
range()
Cria um array com uma sequência crescente ou decrescente.
Versão: PHP 8.4; repository runtime, production runtime not attested
Sintaxe
range(string|int|float $start, string|int|float $end, int|float $step = 1): arrayCria um array com uma sequência crescente ou decrescente. O limite final só aparece se o passo o atingir exatamente. Letras de um byte produzem uma sequência de carateres. O passo zero provoca ValueError e um intervalo grande ocupa memória para todos os elementos. Desde o PHP 8.3 dois limites textuais de um byte, mesmo algarismos, produzem cadeias. Um passo negativo num intervalo crescente provoca ValueError. Cadeias não numéricas mais longas geram E_WARNING e só contam os primeiros bytes.
Assinatura
range(string|int|float $start, string|int|float $end, int|float $step = 1): array
Saída do exemplo
[[5,3,1],["a","c","e"]]
ValueError
[["3","4","5"],["a"],[true,true],"ValueError"]
Exemplos
<?php
echo json_encode([range(5,0,2),range("a","e",2)]), PHP_EOL;
try { range(1,2,0); } catch (ValueError $e) { echo "ValueError"; }
$warnings=[]; set_error_handler(function($n) use (&$warnings){$warnings[]=$n===E_WARNING;return true;});
$bytes=range("ab","ac"); restore_error_handler();
try{range(1,5,-2);}catch(ValueError $e){$negative=get_class($e);}
echo PHP_EOL,json_encode([range("3","5"),$bytes,$warnings,$negative]);
Resultado
[[5,3,1],["a","c","e"]] ValueError [["3","4","5"],["a"],[true,true],"ValueError"]