Posted By

sekihin on 09/18/09


Tagged

php array


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jatubio


Insert into / add element to array at specific position


 / Published in: PHP
 

  1. <?php
  2. function array_insert($array,$pos,$val)
  3. {
  4. $array2 = array_splice($array,$pos);
  5. $array[] = $val;
  6. $array = array_merge($array,$array2);
  7.  
  8. return $array;
  9. }
  10.  
  11. $input = array("red", "green", "blue", "yellow");
  12. array_splice($input, 2);
  13. // $input is now array("red", "green")
  14.  
  15. $input = array("red", "green", "blue", "yellow");
  16. array_splice($input, 1, -1);
  17. // $input is now array("red", "yellow")
  18.  
  19. $input = array("red", "green", "blue", "yellow");
  20. array_splice($input, 1, count($input), "orange");
  21. // $input is now array("red", "orange")
  22.  
  23. $input = array("red", "green", "blue", "yellow");
  24. array_splice($input, -1, 1, array("black", "maroon"));
  25. // $input is now array("red", "green", "blue", "black", "maroon")
  26.  
  27. $input = array("red", "green", "blue", "yellow");
  28. array_splice($input, 3, 0, "purple");
  29. // $input is now array("red", "green", "blue", "purple", "yellow");
  30.  
  31. ?>

Report this snippet  

You need to login to post a comment.