PHP array_slice() 함수
예시
세 번째 배열 요소에서 슬라이스를 시작하고 배열의 나머지 요소를 반환합니다.
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
정의 및 사용
array_slice() 함수는 배열의 선택된 부분을 반환합니다.
참고: 배열에 문자열 키가 있는 경우 반환된 배열은 항상 키를 유지합니다(예제 4 참조).
통사론
array_slice(array, start, length, preserve)
매개변수 값
Parameter | Description |
---|---|
array | Required. Specifies an array |
start | Required. Numeric value. Specifies where the function will start the slice.
0 = the first element.
If this value is set to a negative number, the function will start slicing that far from the last element.
-2 means start at the second last element of the array. |
length | Optional. Numeric value. Specifies the length of the returned array.
If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter.
|
preserve | Optional. Specifies if the function should preserve or reset the keys. Possible values:
|
기술적 세부 사항
반환 값: | 배열의 선택된 부분을 반환 |
---|---|
PHP 버전: | 4+ |
PHP 변경 로그: | 보존 매개변수는 PHP 5.0.2에 추가되었습니다 . |
더 많은 예
실시예 1
두 번째 배열 요소에서 슬라이스를 시작하고 두 개의 요소만 반환합니다.
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2));
?>
실시예 2
음수 시작 매개변수 사용:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,-2,1));
?>
실시예 3
보존 매개변수가 true로 설정된 경우:
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));
?>
실시예 4
문자열 및 정수 키 모두 사용:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"brown");
print_r(array_slice($a,1,2));
$a=array("0"=>"red","1"=>"green","2"=>"blue","3"=>"yellow","4"=>"brown");
print_r(array_slice($a,1,2));
?>
❮ PHP 배열 참조