First of all, I don’t recommend using this type of model, unless for a case study.
Second, even if it is for study I recommend applying some logic:
- Iterate only if the return is greater than one (1)
- Check that the value passed does not exceed the number of items
- Convert to
inteiro
, guaranteed that the user enters a valid number
- Check if the value passed is a number
Initially, applying according to your code, follows updated model;
$retornar = 5; //(int)$_GET['retornar'];
$ccs = array("1", "2"); //código novo (já que você não postou a linha referente ao array)
for($i = 0; $i < $retornar; $i++) {
echo $ccs[$i];
}
See in operation https://3v4l.org/YOSLU
Changing to recommended form
I use 0 to check if 1 has been selected, because the array starts at 0, so just change the loop to 1
<?php
$retornar = 5; //$_GET['retornar'];
$ccs = array("1", "2");
if($retornar > count($ccs)){
die("Quantidade indisponivel");
}
if($retornar == 0){
echo $ccs[0];
}else{
for($i = 0; $i < $retornar; $i++) {
echo $ccs[$i];
}
}
See in operation https://3v4l.org/ntcpZ
This new form is not 100% related to the information, is for you to try to do, since the topic itself has already been answered.
Post the complete code, so I’m missing the array part.
– Mauro Alexandre
No need to convert the
$retornar
for https://3v4l.org/Ke6Cu integer (as stated below). The error is that you are replacing the array$ccs
on the line$ccs = $ccs[$i];
– Valdeir Psr
@Valdeirpsr I have incorporated your comment, but if you prefer to reply separately, and I withdraw from mine, that the +1 is guaranteed.
– Bacco