Array slicing syntax: arr[start:end], where start is the starting index (inclusive) and end is the ending index (exclusive). Practical case: Taking the fruits array as an example, fruits[1:3] takes out the elements from index 1 to index 3 (excluding 3) and returns ['banana', 'cherry']. Other examples: fruits[0:2] takes the first two elements, fruits[2:] takes the elements at index 2 and after, fruits[:3] takes the first three elements, and fruits[-3:] takes the last three elements. It should be noted that slicing returns not a copy of the array but a reference to the original array. Negative indexes are counted from the end of the array.
Array slicing: syntax and practical cases
Grammar:
arr[start:end]
where :
arr
is the array to be sliced. start
is the starting index of the slice (inclusive). end
is the end index of the slice (exclusive). Practical case:
Suppose we have an array of fruits:
fruits = ["apple", "banana", "cherry", "dog"]
Use slices to remove Specified range of fruits in the array:
# 从索引 1 开始到索引 3 结束(不包括索引 3) sliced_fruits = fruits[1:3] # 输出切片结果 print(sliced_fruits)
Output:
['banana', 'cherry']
Other examples:
fruits[0:2]
: Take out the first and second elements of the array. fruits[2:]
: Take out the elements at index 2 and after in the array. fruits[:3]
: Take out the first three elements in the array. fruits[-3:]
: Take out the last three elements in the array. Note:
start
or end
exceeds the array bounds, slicing will return an empty list. The above is the detailed content of What is the syntax for array slicing?. For more information, please follow other related articles on the PHP Chinese website!