배열 array_splice
(PHP 4, PHP 5, PHP 7, PHP 8)
array_splice — 배열의 일부를 제거하고 다른 것으로 교체
설명
array_splice( array &$array, int $offset, ?int $length = null, mixed $replacement = [] ): array
offset
및 length
로 지정된 요소를 array
배열에서 제거하고 제공된 경우 replacement
배열의 요소로 바꿉니다.
메모: array
의 숫자 키는 보존되지 않습니다.
메모: replacement
가 배열이 아닌 경우 하나(예: (array) $replacement
)로 typecast됩니다. 이로 인해 개체 또는 null
replacement
를 사용할 때 예기치 않은 동작이 발생할 수 있습니다.
매개변수
array
- 입력 배열입니다.
offset
offset
이 양수이면 제거된 부분의 시작은array
배열의 시작부터 해당 오프셋에 있습니다.offset
이 음수이면 제거된 부분의 시작은array
배열의 끝에서 해당 오프셋에 있습니다.length
length
가 생략되면offset
에서 배열 끝까지의 모든 것을 제거합니다.length
가 지정되고 양수이면 많은 요소가 제거됩니다.length
가 지정되고 음수이면 제거된 부분의 끝은 배열 끝에서 많은 요소가 됩니다.length
가 지정되고 0이면 요소가 제거되지 않습니다.팁
replacement
도 지정되었을 때offset
에서 배열 끝까지 모든 것을 제거하려면length
에count($input)
를 사용하십시오.replacement
replacement
배열이 지정되면 제거된 요소가 이 배열의 요소로 대체됩니다.offset
과length
가 제거되지 않는 정도이면replacement
배열의 요소가offset
으로 지정된 위치에 삽입됩니다.메모:
replacement
배열의 키는 보존되지 않습니다.replacement
가 하나의 요소일 경우 요소가 배열 자체, 객체 또는null
이 아닌 한array()
또는 대괄호를 그 주위에 둘 필요가 없습니다.
반환 값
추출된 요소로 구성된 배열을 반환합니다.
변경 로그
버전 | 설명 |
---|---|
8.0.0 | length 는 이제 nullable입니다. |
Examples
예제 #1 array_splice() 예제
<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
var_dump($input);
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
var_dump($input);
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
var_dump($input);
$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
var_dump($input);
?>
위의 예는 다음을 출력합니다.
array(2) { [0]=> string(3) "red" [1]=> string(5) "green" } array(2) { [0]=> string(3) "red" [1]=> string(6) "yellow" } array(2) { [0]=> string(3) "red" [1]=> string(6) "orange" } array(5) { [0]=> string(3) "red" [1]=> string(5) "green" [2]=> string(4) "blue" [3]=> string(5) "black" [4]=> string(6) "maroon" }
예제 #2 Equivalent statements to various array_splice() examples
다음 명령문은 동일합니다.
<?php
// append two elements to $input
array_push($input, $x, $y);
array_splice($input, count($input), 0, array($x, $y));
// remove the last element of $input
array_pop($input);
array_splice($input, -1);
// remove the first element of $input
array_shift($input);
array_splice($input, 0, 1);
// insert an element at the start of $input
array_unshift($input, $x, $y);
array_splice($input, 0, 0, array($x, $y));
// replace the value in $input at index $x
$input[$x] = $y; // for arrays where key equals offset
array_splice($input, $x, 1, $y);
?>
기타
- array_merge() - 하나 이상의 배열 병합
- array_slice() - 배열의 조각 추출
- unset() - 주어진 변수 설정 해제