Home  >  Article  >  Backend Development  >  What is the syntax for array slicing?

What is the syntax for array slicing?

WBOY
WBOYOriginal
2024-04-30 08:51:01546browse

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.

What is the syntax for array slicing?

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:

  • Slicing returns not a copy of the array, but a reference to the original array.
  • If start or end exceeds the array bounds, slicing will return an empty list.
  • You can also use negative indexes (counting from the end of the array).

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!

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