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

What is the syntax for array slicing?

WBOY
Release: 2024-04-30 08:51:01
Original
559 people have browsed it

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]
Copy after login

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"]
Copy after login

Use slices to remove Specified range of fruits in the array:

# 从索引 1 开始到索引 3 结束(不包括索引 3)
sliced_fruits = fruits[1:3]

# 输出切片结果
print(sliced_fruits)
Copy after login

Output:

['banana', 'cherry']
Copy after login

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!

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