3v4l.org

run code in 300+ PHP versions simultaneously
<?php $a = [0, 1, 2, 3, 4, 5, 6, 7]; $index = 3; // Result: 1, 2, 3, 4, 5. *example 1 echo pages($a, $index) . "\n"; $index = 0; // Result: 0, 1, 2, 3, 4. *example 2 echo pages($a, $index) . "\n"; $index = 7; // Result: 3, 4, 5, 6, 7. *example 3 echo pages($a, $index) . "\n"; $index = 6; // Result: 3, 4, 5, 6, 7. *example 4 echo pages($a, $index) . "\n"; function pages($a, $index){ if($index >= count($a)-2){ $start = count($a)-5; }elseif($index <=2){ $start = 0; }else{ $start = $index-2; } return implode(", ", array_slice($a, $start, 5)); }
Output for 5.6.38, 7.1.26 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
1, 2, 3, 4, 5 0, 1, 2, 3, 4 3, 4, 5, 6, 7 3, 4, 5, 6, 7

preferences:
156.88 ms | 408 KiB | 5 Q