Return desired amount

-1

Good evening, how can I return values from an array according to the value of a variable? I've tried this way (unsuccessfully):

The goal would be to return the desired amount (given in return GET) of elements of an array

localhost/estudo.php?retornar=5
$retornar = $_GET['retornar'];
for ($i=0; $i < $retornar ; $i++) { 
$ccs = $ccs[$i];
echo $ccs;
}
    
asked by anonymous 14.06.2018 / 23:12

2 answers

1

First of all I do not recommend using this type of model unless it is for case study.

Second, even for study I recommend applying some logic:

  • Iterate only if the return is greater than one (1)
  • Verify that the passed value does not exceed the number of elements
  • Convert to inteiro , guaranteed the user to enter a valid number
  • Verify that the passed value is a number
  • Initially, applying according to your code, follow the updated template;

    $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 working link

    Changing to recommended way

      

    I use 0 to check if 1 was selected because the array starts at 0, so just change the repeat 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 working link

    This new form is not 100% related to the information, it is for you to try to do, since the topic itself has already been answered.

        
    14.06.2018 / 23:37
    4

    The correct answer is the comment of colleague ValdeirPsr. You're spoiling the array in the loop:

    for ($i=0; $i < $retornar ; $i++) { 
       $ccs = $ccs[$i];
       echo $ccs;       // Na segunda iteração, a linha anterior vai falhar
    }
    

    Just change the name of the variable, or use the index already in echo :

    for ($i=0; $i < $retornar ; $i++) { 
       $ccs2 = $ccs[$i];
       echo $ccs2;
    }
    

    Alternative

    If it were not an exercise, but an actual application, you could use what is already ready in PHP, in a single line:

    print_r( array_slice( $ccs, 0, $_GET['retornar'] );
    

    Or even

    $pedaco = array_slice( $ccs, 0, $_GET['retornar'] );
    foreach ($pedaco as $key=>$value) { 
       echo $value;
    }
    

    See working at IDEONE


    The array_slice returns an array extracted from another, determined by an offset and a length

    Manual:

      

    link

        
    14.06.2018 / 23:41