This loop repetition iterates through the entire array and displays the associative key and its value.
foreach ($vetor as $k => $v) {
echo $k.' -> '.$v.PHP_EOL.'<br>';
}
If you wanted to display a particular range, you can only create conditionals within the loop.
Example, if you want to display only the second and third
$c = 1;
foreach ($vetor as $k => $v) {
if ($c == 2 || $c == 3) {
echo $k.' -> '.$v.PHP_EOL.'<br>';
}
$c++;
}
But depending on the case may not be very good, as it would still be iterating the entire array.
It could do otherwise to save memory and processing resources. Even if it's a small economy. What is most interesting is that it makes the routine more dynamic, that is, reusable:
$arr = array(
'Nome'=> 'posicao1',
'Telefone'=> 'posicao2',
'Idade'=> 'posicao3',
'Sexo'=> 'posicao4'
);
function foo($arr, $ini, $end) {
// O terceiro parâmetro como true, preserva os índices.
return array_slice($arr, $ini-1, $end-1, true);
}
// Isso aqui retorna o array "cortado" definindo parâmetros de forma mais simplificada.
$arr = foo($arr, 2, 3);
// Itera tudo normalmente sem precisar fazer firula.
// O laço de repetição fica "livre" de condicionais.
foreach ($arr as $k => $v) {
echo $k.' -> '.$v.PHP_EOL.'<br>';
}
/*
[retorno]
Telefone -> posicao2
Idade -> posicao3
*/
I stress that each solution depends on the situation. In a larger array, for example, more than 20 items, I believe the slice better. In a smaller array, do as in the first example with conditional inside the loop repeat.