Home > Backend Development > PHP Tutorial > PHP array splitting and array joining

PHP array splitting and array joining

WBOY
Release: 2016-07-25 08:54:03
Original
1026 people have browsed it
  1. $fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");

  2. $subset = array_slice($fruits, 3);
  3. print_r($subset);

  4. // output

  5. // Array ( [0] => Pear [1] => Grape [2] => Lemon [3] => Watermelon )
  6. ?>
Copy the code

Then, use the lower negative length:

  1. $fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
  2. $subset = array_slice($fruits, 2, -2);
  3. print_r($subset);

  4. // output

  5. // Array ( [0] => Orange [1] => Pear [2] => Grape )
  6. ?>
Copy code

Splice array array_splice()

The

array_splice() function will delete all elements starting from offset and ending at offset+length in the array, and return the deleted elements in the form of an array. Its form is: array array_splice ( array array , int offset[,length[,array replacement]]) When offset is a positive value, the join will start at the offset position from the beginning of the array. When offset is a negative value, the join will start at the offset position from the end of the array. If the optional length parameter is omitted, all elements starting at offset position and ending at the end of the array will be removed. If length is given and is positive, the join ends at offset + leng th from the beginning of the array. Conversely, if length is given and is negative, the union will end count(input_array)-length from the beginning of the array.

Example:

  1. $fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", " Lemon", "Watermelon");

  2. $subset = array_splice($fruits, 4);

  3. print_r($fruits);

  4. print_r($subset);

  5. < ;p>// output
  6. // Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Pear )
  7. // Array ( [0] => ; Grape [1] => Lemon [2] => Watermelon )
  8. ?>
Copy code

The optional parameter replacement can be used to specify the array to replace the target part.

Example:

  1. $fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", " Lemon", "Watermelon");

  2. $subset = array_splice($fruits, 2, -1, array("Green Apple", "Red Apple"));

  3. print_r($fruits );

  4. print_r($subset);

  5. // output

  6. // Array ( [0] => Apple [1] => Banana [2] => Green Apple [ 3] => Red Apple [4] => Watermelon )
  7. // Array ( [0] => Orange [1] => Pear [2] => Grape [3] => Lemon )
  8. ?>

Copy code


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template