I print the first 5 elements of the array (I know about the function array_slice , but I want to do it without it), but instead of 1,2,3,4,5 I get 2,3,4,5 , but where did 1 go? How to fix? Options with array_slice do not offer.

 $arr=[1,2,3,4,5,6,7,8,9,10]; for($i=0;$i<=count($arr);$i++){ for($j=$arr[0];$j<$arr[4];$j++){ echo $arr[$j]; }break; } 

    2 answers 2

    I do not understand all these difficulties. Need the first five? why then do not bring the first five?

     $arr = range(1,10); for($i=0;$i<=4;$i++){ echo $arr[$i]; } 

    well or for associative

     $arr = range(1,10); $i = 0; foreach($arr as $val) { if ($i++ == 5) break; echo $val; } 

      Well, you yourself have come up with it, using two cycles:

       for($j=$arr[0];$j<$arr[4];$j++){ 

      $j goes from $arr[0] , which is equal to one, to $arr[3] - fours. In other words, the following loop is executed:

       for ($j = 1; $j < 5; $j++) { echo $arr[$j]; } 

      since the array starts with the zero element, it is output from the second to the fifth.

      Of course, you really only need one cycle.

       function arraySliceImplementation($array, $start, $length) { $length = ($start + $length) < sizeof($array) ? $length : sizeof($array) - $start; $copy = []; for ($i = $start; $i < $start + $length; $i++) { $copy[] = $array[$i]; } return $array; } 

      (maybe somewhere wrong with the array boundaries, I always have a bad time with this)

      • your answer seems to me too wise to rewrite it like this, <pre> <code> $ arr = [1,2,3,4,5,6,7,8,9,10]; for ($ i = 0; $ i <= count ($ arr); $ i ++) {for ($ j = 0; $ j <5; $ j ++) {echo $ arr [$ j]; } </ pre> </ code> - pompidu312123131