Is there an easy way to delete an element from an array using PHP, such that PHP를 사용하여 어레이에서 요소를 쉽게 삭제할 수 있는 방법이 있습니까?foreach ($array)
no longer includes that element?더 이상 그 요소를 포함하지 않는가?
I thought that setting it to 나는 그것을 로 설정하는 것이null
would do it, but apparently it does not work.하지만 효과가 없는 것 같습니다.
질문에 대한 답변
There are different ways to delete an array element, where some are more useful for some specific tasks than others.어레이 요소를 삭제하는 방법은 여러 가지가 있으며, 일부 작업은 다른 작업보다 더 유용합니다.
Deleting a single array element단일 배열 요소 삭제
If you want to delete just one array element you can use unset()
or alternatively array_splice()
.어레이 요소를 하나만 삭제하는 경우 또는 를 사용할 수 있습니다.
If you know the value and don’t know the key to delete the element you can use array_search()
to get the key.값을 알고 있지만 키를 얻기 위해 사용할 수 있는 요소를 삭제하는 키를 모르는 경우. This only works if the element does not occur more than once, since 이는 요소가 여러 번 발생하지 않는 경우에만 작동합니다.array_search
returns the first hit only.첫 번째 히트만 반환합니다.
unset()
Note that when you use 를 사용할 때 주의해 주세요.unset()
the array keys won’t change.어레이 키는 변경되지 않습니다. If you want to reindex the keys you can use array_values()
after 나중에 사용할 수 있는 키를 다시 인덱싱하려면unset()
, which will convert all keys to numerically enumerated keys starting from 0.모든 키가 0부터 숫자 열거 키로 변환됩니다.
Code:코드:
$array = [0 => "a", 1 => "b", 2 => "c"]; unset($array[1]); // ↑ Key which you want to delete
Output:출력:
[ [0] => a [2] => c ]
array_splice()
methodarray_splice()
방법
If you use 사용하시는 경우array_splice()
the keys will automatically be reindexed, but the associative keys won’t change — as opposed to 키는 자동으로 다시 인덱싱되지만 관련 키는 변경되지 않습니다.array_values()
, which will convert all keys to numerical keys.모든 키를 숫자 키로 변환합니다.
array_splice()
needs the offset, not the key, as the second parameter.에는 키가 아닌 오프셋이 두 번째 파라미터로 필요합니다.
Code:코드:
$array = [0 => "a", 1 => "b", 2 => "c"]; array_splice($array, 1, 1); // ↑ Offset which you want to delete
Output:출력:
[ [0] => a [1] => c ]
array_splice()
, same as , 과 같은unset()
, take the array by reference., 어레이를 참조해 주세요. You don’t assign the return values of those functions back to the array.이러한 함수의 반환 값은 어레이에 다시 할당하지 않습니다.
Deleting multiple array elements여러 배열 요소 삭제
If you want to delete multiple array elements and don’t want to call 여러 어레이 요소를 삭제하고 호출하지 않는 경우unset()
or 또는array_splice()
multiple times you can use the functions 여러 번 기능을 사용할 수 있습니다.array_diff()
or 또는array_diff_key()
depending on whether you know the values or the keys of the elements which you want to delete.삭제할 요소의 값 또는 키를 알고 있는지 여부에 따라 달라집니다.
array_diff()
methodarray_diff()
방법
If you know the values of the array elements which you want to delete, then you can use 삭제할 배열 요소의 값을 알고 있으면array_diff()
. As before with 이전과 마찬가지로unset()
it won’t change the keys of the array.어레이의 키는 변경되지 않습니다.
Code:코드:
$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"]; $array = array_diff($array, ["a", "c"]); // └────────┘ // Array values which you want to delete
Output:출력:
[ [1] => b ]
array_diff_key()
methodarray_diff_key()
방법
If you know the keys of the elements which you want to delete, then you want to use 삭제할 요소의 키를 알고 있다면array_diff_key()
. You have to make sure you pass the keys as keys in the second parameter and not as values.키를 값이 아닌 두 번째 파라미터의 키로 전달해야 합니다. Keys won’t reindex.키가 색인화되지 않습니다.
Code:코드:
$array = [0 => "a", 1 => "b", 2 => "c"]; $array = array_diff_key($array, [0 => "xy", "2" => "xy"]); // ↑ ↑ // Array keys which you want to delete
Output:출력:
[ [1] => b ]
If you want to use 사용하고 싶은 경우unset()
or 또는array_splice()
to delete multiple elements with the same value you can use array_keys()
to get all the keys for a specific value and then delete all elements.특정 값에 대한 모든 키를 가져온 다음 모든 요소를 삭제하는 데 사용할 수 있는 동일한 값의 여러 요소를 삭제합니다.
array_filter()
methodarray_filter()
방법
If you want to delete all elements with a specific value in the array you can use 배열에서 특정 값을 가진 요소를 모두 삭제하려면array_filter()
..
Code:코드:
$array = [0 => "a", 1 => "b", 2 => "c"]; $array = array_filter($array, static function ($element) { return $element !== "b"; // ↑ // Array value which you want to delete });
Output:출력:
[ [0] => a [1] => c ]
It should be noted that unset()
will keep indexes untouched, which is what you’d expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:는 인덱스를 변경하지 않고 유지합니다.이는 문자열 인덱스(해시 테이블로 배열)를 사용할 때 예상할 수 있는 것이지만 정수 인덱스 어레이를 다룰 때는 매우 놀랄 수 있습니다.
$array = array(0, 1, 2, 3); unset($array[2]); var_dump($array); /* array(3) { [0]=> int(0) [1]=> int(1) [3]=> int(3) } */ $array = array(0, 1, 2, 3); array_splice($array, 2, 1); var_dump($array); /* array(3) { [0]=> int(0) [1]=> int(1) [2]=> int(3) } */
So array_splice()
can be used if you’d like to normalize your integer keys.따라서 정수 키를 정규화하고 싶을 때 사용할 수 있습니다. Another option is using array_values()
after unset()
:또 다른 옵션은 다음 이후를 사용하는 것입니다.
$array = array(0, 1, 2, 3); unset($array[2]); $array = array_values($array); var_dump($array); /* array(3) { [0]=> int(0) [1]=> int(1) [2]=> int(3) } */
// Our initial array $arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red"); print_r($arr); // Remove the elements who's values are yellow or red $arr = array_diff($arr, array("yellow", "red")); print_r($arr);
This is the output from the code above:위의 코드의 출력을 다음에 나타냅니다.
Array ( [0] => blue [1] => green [2] => red [3] => yellow [4] => green [5] => orange [6] => yellow [7] => indigo [8] => red ) Array ( [0] => blue [1] => green [4] => green [5] => orange [7] => indigo )
Now, array_values() will reindex a numerical array nicely, but it will remove all key strings from the array and replace them with numbers.여기서 array_values()는 숫자 배열의 인덱스를 다시 작성하지만 배열에서 모든 키 문자열을 삭제하고 숫자로 대체합니다. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use array_merge():키 이름(문자열)을 유지해야 하는 경우 또는 모든 키가 숫자일 경우 어레이를 다시 인덱싱해야 하는 경우 array_merge()를 사용합니다.
$arr = array_merge(array_diff($arr, array("yellow", "red"))); print_r($arr);
Outputs출력
Array ( [0] => blue [1] => green [2] => green [3] => orange [4] => indigo )
$key = array_search($needle, $array); if ($key !== false) { unset($array[$key]); }
unset($array[$index]);