본문 바로가기

개발/php

배열에서 요소 제거하기

  • array_splice()
  • unset()

array_splice(array &$input, int $offset [, int $length = 0 [, mixed $replacement ]] )
주어진 배열에서 offset 값부터 주어진 length 만큼 요소를 삭제한다.
주의할 점은 인덱스를 이용하는 게 아니라 offset 으로 처리한다.

일반 배열과 연관 배열(키:값으로 요소 구성)에 모두 적용할 수 있다.
일반 배열에서는 적용 후 인덱스가 초기화(0부터 시작) 된다.

$target = array('aa', 'bb', 'cc', 'dd', 'ee', 'ff');
array_splice($target, 3, 1);

array(5) { [0]=> string(2) "aa" [1]=> string(2) "bb" [2]=> string(2) "cc" [3]=> string(2) "ee" [4]=> string(2) "ff" }

$target = array(2=>'aa', 'bb', 'cc', 'dd', 'ee', 'ff');      
array_splice($target, 3, 1); // 인덱스가 아닌 offset 으로 찾은 요소('bb'가 아닌 'dd')를 없앤다. 인덱스를 초기화 한다.

array(5) { [0]=> string(2) "aa" [1]=> string(2) "bb" [2]=> string(2) "cc" [3]=> string(2) "ee" [4]=> string(2) "ff" }

$target = array('1st'=>'aa', '2nd'=>'bb', '3rd'=>'cc', '4th'=>'dd', '5th'=>'ee', '6th'=>'ff');
array_splice($target, 3, 1); // offset으로 찾은 요소(dd)를 제거하지만, 키는 유지된다.

array(5) { ["1st"]=> string(2) "aa" ["2nd"]=> string(2) "bb" ["3rd"]=> string(2) "cc" ["5th"]=> string(2) "ee" ["6th"]=> string(2) "ff" }


unset(maxed $var)
일반 배열이면 인덱스를 이용하여 요소를 제거하고, 연관 배열이면 키를 통해 요소를 제거한다.

$target = array('aa', 'bb', 'cc', 'dd', 'ee', 'ff');
unset($target[3]);

array(5) { [0]=> string(2) "aa" [1]=> string(2) "bb" [2]=> string(2) "cc" [4]=> string(2) "ee" [5]=> string(2) "ff" }

$target = array(2=>'aa', 'bb', 'cc', 'dd', 'ee', 'ff');      
unset($target[3]); // 인덱스로 찾은 요소를 없앤다. 인덱스와 값 모두 지워진다.

array(5) { [2]=> string(2) "aa" [4]=> string(2) "cc" [5]=> string(2) "dd" [6]=> string(2) "ee" [7]=> string(2) "ff" 

$target = array('1st'=>'aa', '2nd'=>'bb', '3rd'=>'cc', '4th'=>'dd', '5th'=>'ee', '6th'=>'ff');
unset($target['3rd']); // 키로 찾은 요소를 제거한다.

array(5) { ["1st"]=> string(2) "aa" ["2nd"]=> string(2) "bb" ["4th"]=> string(2) "dd" ["5th"]=> string(2) "ee" ["6th"]=> string(2) "ff" }

unset()을 사용하면 원하는 요소를 지울 수 있지만 인덱스를 정렬하지 않는다.

unset()으로 요소를 제거하고, array_value()를 사용하여 인덱스를 초기화 할 수 있지만, 사용에 주의가 필요하다. 배열의 모든 값을 돌려주는 함수이므로 매개변수로 주어진 배열의 형태에 관계없이 인덱스가 0부터 시작하는 일반 배열을 얻는다.

요소 접근 방식(offset, index, key)과 처리한 뒤 배열의 index 또는 key를 원하는 형태에 따라 선택할 수 있다.


조금 더 궁금한 부분: 
2차원 배열에서 1차 요소에 적용할 때와 2차 요소에 적용할 때 어떤 결과를 보여줄까?
연관 배열의 값이 배열인 경우는 어떻게 될까?

    


반응형