-
-
$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon"); - $subset = array_slice($fruits, 3);
- print_r($subset);
// output
- // Array ( [0] => Pear [1] => Grape [2] => Lemon [3] => Watermelon )
- ?>
-
-
Copy the code
Then, use the lower negative length:
-
-
- $fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
- $subset = array_slice($fruits, 2, -2);
- print_r($subset);
// output
- // Array ( [0] => Orange [1] => Pear [2] => Grape )
- ?>
-
-
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:
-
-
$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", " Lemon", "Watermelon");
- $subset = array_splice($fruits, 4);
print_r($fruits);
- print_r($subset);
- < ;p>// output
- // Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Pear )
- // Array ( [0] => ; Grape [1] => Lemon [2] => Watermelon )
- ?>
-
-
Copy code
The optional parameter replacement can be used to specify the array to replace the target part.
Example:
-
-
$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", " Lemon", "Watermelon");
- $subset = array_splice($fruits, 2, -1, array("Green Apple", "Red Apple"));
print_r($fruits );
- print_r($subset);
// output
- // Array ( [0] => Apple [1] => Banana [2] => Green Apple [ 3] => Red Apple [4] => Watermelon )
- // Array ( [0] => Orange [1] => Pear [2] => Grape [3] => Lemon )
- ?>
-
Copy code
|