Wednesday 15 February 2012

php - My function doesn't modify the array -


I wrote a function that changes an index array value on the left. It looks like:

  function index_shift ($ array, $ index) {$ n = count ($ array) - 1; ($ I = $ n; $ i & gt; = $ 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 "
"; Print_r ($ array_one); I put the first print_r in the function to see if it works. This does, indicates that the values ​​have been moved to the left ( D is on the fourth and fifth index, all values ​​are taken). But the second print_r outside the function shows that the array is not modified. It looks like a function works, but it does not modify the array. Maybe I'm & amp; should be used?

You are passing an array. If you want to modify the array, then you have to pass the reference of the array:

  function index_shift (& $ array, $ index) {$ n = count ($ array) - 1; ($ I = $ n; $ i & gt; = $ index; $ i -) $ $ array [$ i + 1] = $ array [$ i]; } Print_r ($ array); }   

Here is a link about context through context & amp;:

No comments:

Post a Comment