programing

PHP의 배열에서 요소 삭제

goodjava 2023. 1. 14. 09:24

PHP의 배열에서 요소 삭제

PHP를를 쉽게 할 수 있는 ?foreach ($array)더이 그그 ?소 ?? ???

null을 사용법

어레이 요소를 삭제하는 방법은 여러 가지가 있으며, 일부 작업은 다른 작업보다 더 유용합니다.

단일 배열 요소 삭제

어레이 요소를 하나만 삭제하는 경우 또는 를 사용할 수 있습니다.

값을 알고 있지만 키를 얻기 위해 사용할 수 있는 요소를 삭제하는 키를 모르는 경우.이는 요소가 여러 번 발생하지 않는 경우에만 작동합니다.\array_search첫 번째 히트만 반환합니다.

unset()

「 」를 사용하는 는, 「 」를 해 주세요.unset()어레이 키는 변경되지 않습니다.나중에 사용할 수 있는 키를 다시 인덱싱하려면unset()모든 키가 0부터 숫자 열거 키로 변환됩니다.

코드:

$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
          // ↑ Key which you want to delete

출력:

[
    [0] => a
    [2] => c
]

\array_splice() 방법

「 」를 사용하고 \array_splice()다시 \array_values()이치

\array_splice()에는 키가 아닌 오프셋이 두 번째 파라미터로 필요합니다.

코드:

$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
                   // ↑ Offset which you want to delete

출력:

[
    [0] => a
    [1] => c
]

array_splice()와, 은 ,"unset() 를 취득합니다.이러한 함수의 반환 값은 어레이에 다시 할당하지 않습니다.

여러 배열 요소 삭제

의 하고, 「」를 .unset() ★★★★★★★★★★★★★★★★★」\array_splice() 번 할 수 .\array_diff() ★★★★★★★★★★★★★★★★★」\array_diff_key()삭제할 요소의 값 또는 키를 알고 있는지 여부에 따라 달라집니다.

\array_diff() 방법

있는 「」를 사용할 수 .\array_diff()unset()어레이의 키는 변경되지 않습니다.

코드:

$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = \array_diff($array, ["a", "c"]);
                          // └────────┘
                          // Array values which you want to delete

출력:

[
    [1] => b
]

\array_diff_key() 방법

있는 「삭제하다」를 합니다.\array_diff_key()키를 값이 아닌 두 번째 파라미터의 키로 전달해야 합니다.키가 색인화되지 않습니다.

코드:

$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
                               // ↑           ↑
                               // Array keys which you want to delete

출력:

[
    [1] => b
]

「 」를 사용하고 unset() ★★★★★★★★★★★★★★★★★」\array_splice()특정 값에 대한 모든 키를 가져온 다음 모든 요소를 삭제하는 데 사용할 수 있는 동일한 값의 여러 요소를 삭제합니다.

\array_filter() 방법

내의 " " " 를 사용할 수 .\array_filter().

코드:

$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_filter($array, static function ($element) {
    return $element !== "b";
    //                   ↑
    // Array value which you want to delete
});

출력:

[
    [0] => a
    [1] => c
]

는 인덱스를 변경하지 않고 유지합니다.이는 문자열 인덱스(해시 테이블로 배열)를 사용할 때 예상할 수 있는 것이지만 정수 인덱스 어레이를 다룰 때는 매우 놀랄 수 있습니다.

$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)
} */

따라서 정수 키를 정규화하고 싶을 때 사용할 수 있습니다.또 다른 옵션은 다음 이후를 사용하는 것입니다.

$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);

위의 코드의 출력을 다음에 나타냅니다.

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
)

여기서 array_values()는 숫자 배열의 인덱스를 다시 작성하지만 배열에서 모든 키 문자열을 삭제하고 숫자로 대체합니다.키 이름(문자열)을 유지해야 하는 경우 또는 모든 키가 숫자일 경우 어레이를 다시 인덱싱해야 하는 경우 array_merge()를 사용합니다.

$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);

출력

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]);

또한 이름 있는 요소의 경우:

unset($array["elementName"]);

모든 값이 일의인 수치 인덱스 배열이 있는 경우(또는 값이 일의는 아니지만 특정 값의 모든 인스턴스를 삭제하는 경우), 다음과 같이 array_diff()를 사용하여 일치하는 요소를 삭제할 수 있습니다.

$my_array = array_diff($my_array, array('Value_to_remove'));

예를 들어 다음과 같습니다.

$my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
echo sizeof($my_array) . "\n";
$my_array = array_diff($my_array, array('Charles'));
echo sizeof($my_array);

다음과 같이 표시됩니다.

4
3

이 예에서는 값이 'Charles'인 요소가 삭제됩니다.이는 초기 배열의 크기를 4로 보고하는 sizeof() 호출과 삭제 후 3으로 확인할 수 있습니다.

어레이의 단일 요소 파괴

unset()

$array1 = array('A', 'B', 'C', 'D', 'E');
unset($array1[2]); // Delete known index(2) value from array
var_dump($array1);

출력은 다음과 같습니다.

array(4) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [3]=>
  string(1) "D"
  [4]=>
  string(1) "E"
}

어레이의 인덱스를 다시 작성해야 하는 경우

$array1 = array_values($array1);
var_dump($array1);

다음으로 출력은 다음과 같습니다.

array(4) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "D"
  [3]=>
  string(1) "E"
}

요소를 배열 끝에서 팝업 - 제거된 요소의 값을 반환합니다.

mixed array_pop(array &$array)

$stack = array("orange", "banana", "apple", "raspberry");
$last_fruit = array_pop($stack);
print_r($stack);
print_r('Last Fruit:'.$last_fruit); // Last element of the array

출력은 다음과 같습니다.

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)
Last Fruit: raspberry

배열에서 첫 번째 요소(빨간색)를 제거하고 제거된 요소의 값을 반환합니다.

mixed array_shift ( array &$array )

$color = array("a" => "red", "b" => "green" , "c" => "blue");
$first_color = array_shift($color);
print_r ($color);
print_r ('First Color: '.$first_color);

출력은 다음과 같습니다.

Array
(
    [b] => green
    [c] => blue
)
First Color: red
<?php
    $stack = ["fruit1", "fruit2", "fruit3", "fruit4"];
    $fruit = array_shift($stack);
    print_r($stack);

    echo $fruit;
?>

출력:

[
    [0] => fruit2
    [1] => fruit3
    [2] => fruit4
]

fruit1

인덱스가 지정된 경우:

$arr = ['a', 'b', 'c'];
$index = 0;    
unset($arr[$index]);  // $arr = ['b', 'c']

인덱스 대신 값이 있는 경우:

$arr = ['a', 'b', 'c'];

// search the value to find index
// Notice! this will only find the first occurrence of value
$index = array_search('a', $arr);

if($index !== false){
   unset($arr[$index]);  // $arr = ['b', 'c']
}

if는 '만일'이 '만일'인 경우index수 없습니다.unset()그러면 어레이의 첫 번째 요소가 자동으로 삭제됩니다.이러한 요소는 필요 없습니다.

어레이에서 여러 값을 삭제해야 하는 경우 해당 어레이의 엔트리가 객체 또는 구조화 데이터인 경우 를 사용하는 것이 가장 좋습니다.콜백 함수에서 true를 반환하는 엔트리는 유지됩니다.

$array = [
    ['x'=>1,'y'=>2,'z'=>3], 
    ['x'=>2,'y'=>4,'z'=>6], 
    ['x'=>3,'y'=>6,'z'=>9]
];

$results = array_filter($array, function($value) {
    return $value['x'] > 2; 
}); //=> [['x'=>3,'y'=>6,z=>'9']]

연관 배열에서 여러 요소를 제거해야 할 경우 array_diff_key()를 사용할 수 있습니다(여기서 array_flip()와 함께 사용).

$my_array = array(
  "key1" => "value 1",
  "key2" => "value 2",
  "key3" => "value 3",
  "key4" => "value 4",
  "key5" => "value 5",
);

$to_remove = array("key2", "key4");

$result = array_diff_key($my_array, array_flip($to_remove));

print_r($result);

출력:

Array ( [key1] => value 1 [key3] => value 3 [key5] => value 5 ) 

어소시에이션 어레이

연관 배열의 경우 다음을 사용합니다.

$arr = array('a' => 1, 'b' => 2, 'c' => 3);
unset($arr['b']);

// RESULT: array('a' => 1, 'c' => 3)

숫자 배열

숫자 배열의 경우 다음을 사용합니다.

$arr = array(1, 2, 3);
array_splice($arr, 1, 1);

// RESULT: array(0 => 1, 1 => 3)

메모

숫자 배열에 를 사용하면 오류가 발생하지는 않지만 인덱스가 흐트러집니다.

$arr = array(1, 2, 3);
unset($arr[1]);

// RESULT: array(0 => 1, 2 => 3)

unset()는 지정된 변수를 삭제합니다.

unset()함수 내부는 파괴하려는 변수의 유형에 따라 달라질 수 있습니다.

가 " " " 인 unset()함수의 내부에서는 로컬 변수만 파기됩니다.는 이전과 합니다.unset()을 사용하다

<?php
    function destroy_foo()
    {
        global $foo;
        unset($foo);
    }

    $foo = 'bar';
    destroy_foo();
    echo $foo;
?>

상기 코드의 답변은 bar입니다.

로 으로.unset()" " " " 부수부부 。

<?php
    function foo()
    {
        unset($GLOBALS['bar']);
    }

    $bar = "something";
    foo();
?>
// Remove by value
function removeFromArr($arr, $val)
{
    unset($arr[array_search($val, $arr)]);
    return array_values($arr);
}

솔루션:

  1. 1개의 요소를 삭제하려면 unset()사용합니다.
unset($array[3]);
unset($array['foo']);
  1. 연속되지 않은 여러 요소를 삭제하려면 unset()사용합니다.
unset($array[3], $array[5]);
unset($array['foo'], $array['bar']);
  1. 연속된 여러 요소를 삭제하려면 array_splice()를 사용합니다.
array_splice($array, $offset, $length);

상세설명:

이러한 함수를 사용하면 이러한 요소에 대한 모든 참조가 PHP에서 제거됩니다.키를 배열에 유지하되 값을 비워두려면 다음 요소에 빈 문자열을 할당합니다.

$array[3] = $array['foo'] = '';

구문 외에 unset()을 사용하는 것과 요소에 "를 할당하는 것 사이에는 논리적인 차이가 있습니다.첫 번째가 말한다This doesn't exist anymore,, 두 는 '''로 되어 있다'''This still exists, but its value is the empty string.

숫자를 다루는 경우 0을 할당하는 것이 더 나은 대안이 될 수 있습니다.따라서 XL1000 스프로킷 모델의 생산을 중단하면 다음과 같이 재고를 업데이트합니다.

unset($products['XL1000']);

그러나 일시적으로 XL1000 스프로켓이 바닥났지만 이번 주 후반에 공장으로부터 새로운 화물을 받을 예정이었다면 다음과 같이 하는 것이 좋습니다.

$products['XL1000'] = 0;

요소를 설정 해제()하면 PHP는 루프가 정상적으로 동작하도록 어레이를 조정합니다.부족한 구멍을 메우기 위해 어레이를 압축하지 않습니다.모든 어레이가 숫자인 것처럼 보여도 연관성이 있다고 하는 것은, 이러한 의미입니다.다음은 예를 제시하겠습니다.

// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
print $animals[1];  // Prints 'bee'
print $animals[2];  // Prints 'cat'
count($animals);    // Returns 6

// unset()
unset($animals[1]); // Removes element $animals[1] = 'bee'
print $animals[1];  // Prints '' and throws an E_NOTICE error
print $animals[2];  // Still prints 'cat'
count($animals);    // Returns 5, even though $array[5] is 'fox'

// Add a new element
$animals[ ] = 'gnu'; // Add a new element (not Unix)
print $animals[1];  // Prints '', still empty
print $animals[6];  // Prints 'gnu', this is where 'gnu' ended up
count($animals);    // Returns 6

// Assign ''
$animals[2] = '';   // Zero out value
print $animals[2];  // Prints ''
count($animals);    // Returns 6, count does not decrease

배열을 조밀하게 채워진 숫자 배열로 압축하려면 array_values()를 사용합니다.

$animals = array_values($animals);

또는 array_splice()는 홀을 남기지 않도록 어레이를 자동으로 재인덱스화합니다.

// Create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
array_splice($animals, 2, 2);
print_r($animals);
Array
(
    [0] => ant
    [1] => bee
    [2] => elk
    [3] => fox
)

이 기능은 어레이를 큐로 사용할 때 랜덤 액세스를 허용하면서 큐에서 항목을 제거하는 경우에 유용합니다.배열에서 첫 번째 또는 마지막 요소를 안전하게 제거하려면 각각 array_shift()array_pop()을 사용합니다.

기본 기능을 따릅니다.

  • PHP: 설정 해제

unset()는 지정된 변수를 삭제합니다.자세한 것은, PHP 의 설정 해제

$Array = array("test1", "test2", "test3", "test3");

unset($Array[2]);
  • PHP: array_pop

array_pop()함수는 배열의 마지막 요소를 삭제합니다.자세한 내용은 PHP array_pop을 참조하십시오.

$Array = array("test1", "test2", "test3", "test3");

array_pop($Array);
  • PHP: array_splice

array_splice()함수는 선택한 요소를 배열에서 제거하고 새 요소로 바꿉니다.자세한 내용은 PHP array_splice를 참조하십시오.

$Array = array("test1", "test2", "test3", "test3");

array_splice($Array,1,2);
  • PHP: array_shift

array_shift()함수는 배열에서 첫 번째 요소를 제거합니다.자세한 내용은 PHP array_shift를 참조하십시오.

$Array = array("test1", "test2", "test3", "test3");

array_shift($Array);

변수 속성을 가진 특정 객체가 있다고 말씀드리고 싶습니다(기본적으로 테이블을 매핑하고 테이블의 열을 변경했기 때문에 테이블을 반영하는 객체의 속성도 달라집니다).

class obj {
    protected $fields = array('field1','field2');
    protected $field1 = array();
    protected $field2 = array();
    protected loadfields(){}
    // This will load the $field1 and $field2 with rows of data for the column they describe
    protected function clearFields($num){
        foreach($fields as $field) {
            unset($this->$field[$num]);
            // This did not work the line below worked
            unset($this->{$field}[$num]); // You have to resolve $field first using {}
        }
    }
}

$fields변경 시 코드 전체를 볼 필요가 없습니다.클래스의 선두를 보고 속성 목록과 $fields 배열 내용을 변경하여 새로운 속성을 반영합니다.

다음과 같은 배열이 있다고 가정합니다.

Array
(
    [user_id] => 193
    [storage] => 5
)

storage 하다

unset($attributes['storage']);
$attributes = array_filter($attributes);

그 결과, 다음과 같이 됩니다.

Array
(
    [user_id] => 193
)

인덱스의 순서를 유지하면서 배열의 첫 번째 항목을 제거하는 방법과 첫 번째 항목의 키 이름을 모르는 경우 두 가지 방법이 있습니다.

솔루션 #1

// 1 is the index of the first object to get
// NULL to get everything until the end
// true to preserve keys
$array = array_slice($array, 1, null, true);

솔루션 #2

// Rewinds the array's internal pointer to the first element
// and returns the value of the first array element.
$value = reset($array);
// Returns the index element of the current array position
$key = key($array);
unset($array[$key]);

이 샘플 데이터의 경우:

$array = array(10 => "a", 20 => "b", 30 => "c");

다음과 같은 결과가 필요합니다.

array(2) {
  [20]=>
  string(1) "b"
  [30]=>
  string(1) "c"
}

어레이에서 여러 fragment화된 요소를 설정 해제()

한편, 「 」는, 「 」, 「 」의 사이에unset()번 되었지만, .unset()는 복수의 에, 하지 않은 할 수 .「 」 、 「1 」 、 「 1 」 。

// Delete multiple, noncontiguous elements from an array
$array = [ 'foo', 'bar', 'baz', 'quz' ];
unset( $array[2], $array[3] );
print_r($array);
// Output: [ 'foo', 'bar' ]

동적으로 설정 해제()

unset()은 삭제할 키의 배열을 받아들이지 않기 때문에 다음 코드는 실패합니다(unset()를 동적으로 사용하는 것이 약간 쉬워집니다).

$array = range(0,5);
$remove = [1,2];
$array = unset( $remove ); // FAILS: "unexpected 'unset'"
print_r($array);

대신 foreach 루프에서 unset()를 동적으로 사용할 수 있습니다.

$array = range(0,5);
$remove = [1,2];
foreach ($remove as $k=>$v) {
    unset($array[$v]);
}
print_r($array);
// Output: [ 0, 3, 4, 5 ]

어레이를 복사하여 어레이 키를 삭제합니다.

아직 언급되지 않은 또 다른 관행도 있다.경우에 따라 특정 어레이 키를 삭제하는 가장 간단한 방법은 $array1을 $array2에 복사하는 것입니다.

$array1 = range(1,10);
foreach ($array1 as $v) {
    // Remove all even integers from the array
    if( $v % 2 ) {
        $array2[] = $v;
    }
}
print_r($array2);
// Output: [ 1, 3, 5, 7, 9 ];

텍스트 문자열에도 같은 프랙티스가 적용됩니다.

$array1 = [ 'foo', '_bar', 'baz' ];
foreach ($array1 as $v) {
    // Remove all strings beginning with underscore
    if( strpos($v,'_')===false ) {
        $array2[] = $v;
    }
}
print_r($array2);
// Output: [ 'foo', 'baz' ]

다음 키를 기준으로 어레이 요소 제거:

하다를 사용하세요.unset하다

$a = array(
       'salam',
       '10',
       1
);

unset($a[1]);

print_r($a);

/*

    Output:

        Array
        (
            [0] => salam
            [2] => 1
        )

*/

값을 기준으로 배열 요소 제거:

하다를 사용하세요.array_search요소 키를 가져오고 위의 방법을 사용하여 다음과 같이 배열 요소를 제거합니다.

$a = array(
       'salam',
       '10',
       1
);

$key = array_search(10, $a);

if ($key !== false) {
    unset($a[$key]);
}

print_r($a);

/*

    Output:

        Array
        (
            [0] => salam
            [2] => 1
        )

*/

편집

개체가 해당 배열에 있는 것으로 간주할 수 없는 경우 다음과 같이 체크를 추가해야 합니다.

if(in_array($object,$array)) unset($array[array_search($object,$array)]);

원답

어레이의 특정 개체를 해당 개체의 참조로 제거하려면 다음을 수행할 수 있습니다.

unset($array[array_search($object,$array)]);

예:

<?php
class Foo
{
    public $id;
    public $name;
}

$foo1 = new Foo();
$foo1->id = 1;
$foo1->name = 'Name1';

$foo2 = new Foo();
$foo2->id = 2;
$foo2->name = 'Name2';

$foo3 = new Foo();
$foo3->id = 3;
$foo3->name = 'Name3';


$array = array($foo1,$foo2,$foo3);
unset($array[array_search($foo2,$array)]);

echo '<pre>';
var_dump($array);
echo '</pre>';
?>

결과:

array(2) {
[0]=>
    object(Foo)#1 (2) {
        ["id"]=>
        int(1)
        ["name"]=>
        string(5) "Name1"
    }
[2]=>
    object(Foo)#3 (2) {
        ["id"]=>
        int(3)
        ["name"]=>
        string(5) "Name3"
    }
}

개체가 여러 번 발생할 경우 처음 발생한 개체만 제거됩니다!

다음 코드를 사용합니다.

$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);
<?php
    // If you want to remove a particular array element use this method
    $my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");

    print_r($my_array);
    if (array_key_exists("key1", $my_array)) {
        unset($my_array['key1']);
        print_r($my_array);
    }
    else {
        echo "Key does not exist";
    }
?>

<?php
    //To remove first array element
    $my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
    print_r($my_array);
    $new_array = array_slice($my_array, 1);
    print_r($new_array);
?>


<?php
    echo "<br/>    ";
    // To remove first array element to length
    // starts from first and remove two element
    $my_array = array("key1"=>"value 1", "key2"=>"value 2", "key3"=>"value 3");
    print_r($my_array);
    $new_array = array_slice($my_array, 1, 2);
    print_r($new_array);
?>

산출량

 Array ( [key1] => value 1 [key2] => value 2 [key3] =>
 value 3 ) Array (    [key2] => value 2 [key3] => value 3 )
 Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
 Array ( [key2] => value 2 [key3] => value 3 )
 Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 )
 Array ( [key2] => value 2 [key3] => value 3 )

이 문제에 대해 unset($ar[$i])을 사용하는 것보다 더 우아한 해결책이 있는지 알고 싶어서 왔습니다.실망스럽게도 이 답변들은 틀렸거나 모든 가장자리를 커버하지는 않는다.

array_diff()가 동작하지 않는 이유는 다음과 같습니다.키는 배열 내에서 고유하지만 요소가 항상 고유하지는 않습니다.

$arr = [1,2,2,3];

foreach($arr as $i => $n){
    $b = array_diff($arr,[$n]);
    echo "\n".json_encode($b);
}

결과...

[2,2,3]
[1,3]
[1,2,2] 

두 요소가 동일한 경우 제거됩니다.이는 array_search() 및 array_flip()에도 적용됩니다.

array_slice() 및 array_splice()에 대한 답변은 많았지만 이러한 함수는 숫자 배열에서만 작동합니다.여기서 질문에 대한 답이 나오지 않는 경우, 내가 알고 있는 모든 답변이 유효합니다.그러면 여기 도움이 되는 솔루션이 있습니다.

$arr = [1,2,3];

foreach($arr as $i => $n){
    $b = array_merge(array_slice($arr,0,$i),array_slice($arr,$i+1));
    echo "\n".json_encode($b);
}

Results...

[2,3];
[1,3];
[1,2];

unset($ar[$i])는 관련지어 어레이와 숫자 어레이 모두에서 동작하기 때문에 이 질문에는 답변할 수 없습니다.

이 솔루션은 키를 비교하고 수치 어레이와 관련지어 어레이를 모두 처리하는 도구와 비교합니다.여기에는 array_diff_uassoc()를 사용합니다.이 함수는 콜백 함수의 키를 비교합니다.

$arr = [1,2,2,3];
//$arr = ['a'=>'z','b'=>'y','c'=>'x','d'=>'w'];
foreach($arr as $key => $n){
    $b = array_diff_uassoc($arr, [$key=>$n], function($a,$b) {
        if($a != $b){
            return 1;
        }
    });
    echo "\n".json_encode($b);
}    

결과.....

[2,2,3];
[1,2,3];
[1,2,2];

['b'=>'y','c'=>'x','d'=>'w'];
['a'=>'z','c'=>'x','d'=>'w'];
['a'=>'z','b'=>'y','d'=>'w'];
['a'=>'z','b'=>'y','c'=>'x'];

언급URL : https://stackoverflow.com/questions/369602/deleting-an-element-from-an-array-in-php