# Untitled

By: a guest on Jul 18th, 2012  |  syntax: None  |  size: 1.50 KB  |  hits: 5  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. How to make an array cycle?
2. // In
3. \$arr = [0, 1, 2, 4, 5];
4. // Out
5. \$cycled_arr = [5, 1, 2, 3, 4, 0];
6.
7. \$arr = array(0, 1, 2, 3, 4, 5);
8.
9. // It cycles once
10. function array_start_push(\$array){
11.     return array_merge( array(array_pop(\$array)), \$array);
12. }
13. // This function must cycle array \$times times
14. function cycleArray(\$times,&\$glArr){
15.     if (!isset(\$times)){
16.         \$result = \$glArr;
17.     } else {
18.         for (\$loc = 0; \$loc <= \$times; \$loc++) {
19.         \$result = array_start_push(\$glArr);
20.         \$glArr = \$result;
21.     }
22.     return \$result;
23. }
24.
25. \$hmm = cycleArray(\$arr);
26.
27. echo "<pre>";
28. var_dump(\$hmm);
29. echo "</pre>";
30.
31. // In array
32. \$arr = array(0, 1, 2, 3, 4, 5);
33.
34. // Circle array once
35. function array_start_push(\$array){
36.     return array_merge( array(array_pop(\$array)), \$array);
37. }
38. // Cycling \$times times
39. function cycleArray(\$times,&\$glArr){
40.         for (\$loc = 0; \$loc <= \$times; \$loc++) {
41.             \$result = array_start_push(\$glArr);
42.             \$glArr = \$result;
43.         }
44.     return \$result;
45. }
46.
47. \$hmm = cycleArray(0,\$arr);
48.
49. echo "<pre>";
50. var_dump(\$hmm);
51. echo "</pre>";
52.
53. function cycleArray(\$times, \$glArr){
54.   for(\$i = 0; \$i < \$times; \$i++)
55.   {
56.     //\$glArr[] = array_shift(\$glArr);
57.     array_unshift(\$glArr, array_pop(\$glArr));
58.   }
59.   return \$glArr;
60. }
61.
62. function cycle(array \$arr, \$steps) {
63.     return array_merge(array_slice(\$arr, \$steps), array_slice(\$arr, 0, \$steps));
64. }
65.
66. var_dump(cycle(array(1, 2, 3, 4, 5), 3));
67.
68. array(5) {
69.   [0]=> int(4)
70.   [1]=> int(5)
71.   [2]=> int(1)
72.   [3]=> int(2)
73.   [4]=> int(3)
74. }