I have written a function that shifts array values one index to the left. It looks like this:
function index_shift($array, $index){
$n = count($array) - 1;
for($i = $n; $i >= $index; $i --){
$array[$i + 1] = $array[$i];
}
print_r($array);
}
$array_one = array("a","b","c","d","e","f","g");
index_shift($array_one, 3);
echo "<br />";
print_r($array_one);
I inserted the first print_r
into the function to see if it works. It does, it shows that the values have been shifted to the left (d
is on the 4th and 5th index, all the values are moved). But the second print_r
outside the function shows that the array is not modified. Seems like the function works as it has to, but it doesn't modify the array. Maybe I should use a &
somewhere?
You are passing an array. If you want to modify the array itself you need to pass the reference to the array:
function index_shift(&$array, $index){
$n = count($array) - 1;
for($i = $n; $i >= $index; $i --){
$array[$i + 1] = $array[$i];
}
print_r($array);
}
Here is a link about reference passing using &: http://php.net/manual/en/language.references.pass.php
Alternatively, you can return the array value back to the function call:
function index_shift($array, $index){
$n = count($array) - 1;
for($i = $n; $i >= $index; $i --){
$array[$i + 1] = $array[$i];
}
return $array;
}
$array_one = array("a","b","c","d","e","f","g");
$array_two=index_shift($array_one, 3);
echo "<br />";
print_r($array_one);
print_r($array_two);