Posted By

sekihin on 01/05/11


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
 

URL: http://www.ferolen.com/blog/insert-into-add-element-to-array-at-specific-position-php/

Usually, we can search and identify PHP function just by looking at it’s name which denotes what a function does. For example arraypop(), arraypush(), arraysearch(), arrayreverse(), etc. But how about inserting an element into the middle of an array?

arraysplice(array &$input, int $offset [, int $length= 0 [, mixed $replacement]] ) is the function that you are looking for. Format to use this function to add new element at certain position in an array is arraysplice($array, $insertposition, 0, $elementto_insert);. See below for an example of how this function behaves.

  1. <?php
  2. $input = array("red", "green", "blue", "yellow");
  3. array_splice($input, 2);
  4. // $input is now array("red", "green")
  5.  
  6. $input = array("red", "green", "blue", "yellow");
  7. array_splice($input, 1, -1);
  8. // $input is now array("red", "yellow")
  9.  
  10. $input = array("red", "green", "blue", "yellow");
  11. array_splice($input, 1, count($input), "orange");
  12. // $input is now array("red", "orange")
  13.  
  14. $input = array("red", "green", "blue", "yellow");
  15. array_splice($input, -1, 1, array("black", "maroon"));
  16. // $input is now array("red", "green", "blue", "black", "maroon")
  17.  
  18. $input = array("red", "green", "blue", "yellow");
  19. array_splice($input, 3, 0, "purple");
  20. // $input is now array("red", "green", "blue", "purple", "yellow");
  21. ?>

Report this snippet  

You need to login to post a comment.