If you have your error reporting switched on, you will see three of these Notices:
Notice: Only variables should be passed by reference...
This is because you are passing the output of array_slice()
as the referenced parameter; to fix this you must declare `array_slice()'s output as a variable before passing it in.
The fact that you are seeing three Notices actually indicates that your recursive technique IS traverse as far as intended and doing the work, but the resultant element swapping is not being applied to the previous calls on $s
-- IOW all of the subsequent recursive modifications are lost. (Demo)
@arkascha supplied the necessary fixes to your script about an hour before me, but I might write it slightly differently.
Code: (Demo)
function swapOutermost(&$a) {
$size = count($a);
if ($size > 1) {
$innerElements = array_slice($a, 1, -1);
swapOutermost($innerElements);
$a = array_merge(
[$a[$size - 1]], // last is put first
$innerElements, // recursed reference in the middle
[$a[0]] // first is put last
);
}
}
count()
only once per recursive call -- arkascha fixed this
- no
return
is written
-1
as the 3rd parameter of array_slice()
has the same effect as your $len - 2
.
Here is a recursive technique that only uses iterated count()
calls -- no slicing or merging because it is passing the entire original input array each time. Only the targeted indexes change during recursion. I am swapping based on index incrementation using Symmetric Array Destructuring (a tool available from PHP7.1 and up).
Code: (Demo)
function swapOutermost(&$a, $i = 0) {
$last = count($a) - 1 - $i;
if ($i < $last) {
[$a[$i], $a[$last]] = [$a[$last], $a[$i]];
swapOutermost($a, ++$i);
}
}
swapOutermost($array);
...of course, since the count never changes, it would be more efficient to just pass it in once and reuse it.
function swapOutermost(&$a, $count, $i = 0) {
$last = $count - 1 - $i;
if ($i < $last) {
[$a[$i], $a[$last]] = [$a[$last], $a[$i]];
swapOutermost($a, $count, ++$i);
}
}
swapOutermost($array, count($array));
Now, your original snippet uses modification by reference, but you don't explicitly demand this in your question requirements -- only that recursion must be used. If you might entertain a recursive function that returns the variable instead (because, say, you want to be able to nest this call inside of another function), then here is one way that passes an ever shorter array with each level of recursion (as your original did):
Code: (Demo)
function recursiveArrayReverse($a) {
$size = count($a);
if ($size < 2) {
return $a;
}
return array_merge(
[$a[$size - 1]],
recursiveArrayReverse(
array_slice($a, 1, -1)
),
[$a[0]]
);
}
$array = [1, 2, 3, 4, 5, 6, 7];
$array = recursiveArrayReverse($array);