Home  >  Article  >  Backend Development  >  Two functions for splitting arrays in php (array_slice(), array_splice())

Two functions for splitting arrays in php (array_slice(), array_splice())

WBOY
WBOYOriginal
2016-07-25 09:04:341570browse
  1. $input = array("a", "b", "c", "d", "e");

  2. $output = array_slice($input, -2, 1); // returns "d"
  3. $ output = array_slice($input, 0, 3); // returns "a", "b", and "c"

  4. // note the differences in the array keys

  5. print_r(array_slice ($input, 2, -1));
  6. print_r(array_slice($input, 2, -1, true));
  7. ?>

Copy the code

The above example will output : Array ( [0] => c [1] => d ) Array ( [2] => c [3] => d )

2.array_splice()

Carries three parameters, the same as above, and its function is to delete the subarray with length starting from offset.

Example:

  1. $input = array("red", "green", "blue", "yellow");
  2. array_splice($input, 2);
  3. // $input is now array("red", "green")

  4. $input = array("red", "green", "blue", "yellow");

  5. array_splice($ input, 1, -1);
  6. // $input is now array("red", "yellow")

  7. $input = array("red", "green", "blue ", "yellow");

  8. array_splice($input, 1, count($input), "orange");
  9. // $input is now array("red", "orange")

  10. < ;p>$input = array("red", "green", "blue", "yellow");
  11. array_splice($input, -1, 1, array("black", "maroon"));
  12. / / $input is now array("red", "green",
  13. // "blue", "black", "maroon")

  14. $input = array("red", " green", "blue", "yellow");

  15. array_splice($input, 3, 0, "purple");
  16. // $input is now array("red", "green",
  17. // "blue" , "purple", "yellow");
  18. ?>

Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn