简体   繁体   English

从 PHP 中的数组中删除一个元素

[英]Deleting an element from an array in PHP

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?有没有一种简单的方法可以使用 PHP 从数组中删除一个元素,以便foreach ($array)不再包含该元素?

I thought that setting it to null would do it, but apparently it does not work.我认为将它设置为null就可以了,但显然它不起作用。

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() .如果您只想删除一个数组元素,您可以使用unset()\\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.如果您知道值但不知道删除元素的键,则可以使用\\array_search()获取键。 This only works if the element does not occur more than once, since \\array_search returns the first hit only.这仅在元素出现多次时才有效,因为\\array_search仅返回第一个命中。

unset()

Note that when you use unset() the array keys won't change.请注意,当您使用unset() ,数组键不会改变。 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.如果您想重新索引键,您可以在unset()之后使用\\array_values() unset() ,这会将所有键转换为从 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() method \\array_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()键将自动重新索引,但关联键不会改变 - 与\\array_values()相反,它将所有键转换为数字键。

\\array_splice() needs the offset , not the key , as the second parameter. \\array_splice()需要offset ,而不是key ,作为第二个参数。

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. array_splice()unset()相同,通过引用获取数组。 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.如果你想删除多个数组元素并且不想多次调用unset()\\array_splice()你可以使用函数\\array_diff()\\array_diff_key()取决于你是否知道值或键要删除的元素。

\\array_diff() method \\array_diff()方法

If you know the values of the array elements which you want to delete, then you can use \\array_diff() .如果您知道要删除的数组元素的值,则可以使用\\array_diff() As before with unset() it won't change the keys of the array.与之前使用unset()它不会更改数组的键。

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() method \\array_diff_key()方法

If you know the keys of the elements which you want to delete, then you want to use \\array_diff_key() .如果您知道要删除的元素的键,那么您想使用\\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.如果您想使用unset()\\array_splice()删除具有相同值的多个元素,您可以使用\\array_keys()获取特定值的所有键,然后删除所有元素。

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:应该注意的是unset()将保持索引不变,这是您在使用字符串索引(数组作为哈希表)时所期望的,但在处理整数索引数组时可能会非常令人惊讶:

$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.因此,如果您想规范化整数键,可以使用array_splice() Another option is using array_values() after unset() :另一种选择是在unset()之后使用array_values() 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]);

If you have a numerically indexed array where all values are unique (or they are non-unique but you wish to remove all instances of a particular value), you can simply use array_diff() to remove a matching element, like this:如果您有一个数字索引数组,其中所有值都是唯一的(或者它们不唯一但您希望删除特定值的所有实例),则可以简单地使用 array_diff() 删除匹配元素,如下所示:

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

For example:例如:

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

This displays the following:这将显示以下内容:

4
3

In this example, the element with the value 'Charles' is removed as can be verified by the sizeof() calls that report a size of 4 for the initial array, and 3 after the removal.在此示例中,删除了值为 'Charles' 的元素,这可以通过 sizeof() 调用进行验证,该调用报告初始数组的大小为 4,删除后为 3。

此外,对于命名元素:

unset($array["elementName"]);

Destroy a single element of an array销毁数组的单个元素

unset()

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

The output will be:输出将是:

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

If you need to re index the array:如果需要重新索引数组:

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

Then the output will be:然后输出将是:

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

Pop the element off the end of array - return the value of the removed element从数组末尾弹出元素- 返回删除元素的值

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

The output will be输出将是

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

Remove the first element (red) from an array , - return the value of the removed element从数组中移除第一个元素(红色) , - 返回移除元素的值

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

The output will be:输出将是:

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

    echo $fruit;
?>

Output:输出:

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

fruit1

To avoid doing a search one can play around with array_diff :为了避免进行搜索,可以使用array_diff

$array = array(3, 9, 11, 20);
$array = array_diff($array, array(11) ); // removes 11

In this case one doesn't have to search/use the key.在这种情况下,不必搜索/使用密钥。

If the index is specified:如果指定了索引:

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

If we have value instead of index:如果我们有值而不是索引:

$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']
}

The if condition is necessary because if index is not found, unset() will automatically delete the first element of the array which is not what we want. if条件是必要的,因为如果没有找到indexunset()将自动删除数组的第一个不是我们想要的元素。

If you have to delete multiple values in an array and the entries in that array are objects or structured data, array_filter() is your best bet.如果您必须删除数组中的多个值并且该数组中的条目是对象或结构化数据,则array_filter()是您最好的选择。 Those entries that return a true from the callback function will be retained.那些从回调函数返回 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']]

Associative arrays关联数组

For associative arrays, use unset :对于关联数组,请使用unset

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

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

Numeric arrays数字数组

For numeric arrays, use array_splice :对于数值数组,使用array_splice

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

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

Note笔记

Using unset for numeric arrays will not produce an error, but it will mess up your indexes:对数字数组使用unset不会产生错误,但会弄乱索引:

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

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

If you need to remove multiple elements from an associative array, you can use array_diff_key() (here used with array_flip() ):如果需要从关联数组中删除多个元素,可以使用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);

Output:输出:

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

unset() destroys the specified variables. unset()销毁指定的变量。

The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.函数内unset()的行为可能因您试图销毁的变量类型而异。

If a globalized variable is unset() inside of a function, only the local variable is destroyed.如果函数内部的一个全局变量是unset() ,则只有局部变量会被销毁。 The variable in the calling environment will retain the same value as before unset() was called.调用环境中的变量将保留与调用unset()之前相同的值。

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

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

The answer of the above code will be bar .上面代码的答案是bar

To unset() a global variable inside of a function: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);
}

Solutions:解决方案:

  1. To delete one element, use unset() :要删除一个元素,请使用unset()
 unset($array[3]); unset($array['foo']);
  1. To delete multiple noncontiguous elements, also use unset() :要删除多个不连续的元素,还可以使用unset()
 unset($array[3], $array[5]); unset($array['foo'], $array['bar']);
  1. To delete multiple contiguous elements, use array_splice() :要删除多个连续元素,请使用array_splice()
 array_splice($array, $offset, $length);

Further explanation:进一步解释:

Using these functions removes all references to these elements from PHP.使用这些函数可以从 PHP 中删除对这些元素的所有引用。 If you want to keep a key in the array, but with an empty value, assign the empty string to the element:如果您想在数组中保留一个键,但值为空,请将空字符串分配给元素:

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

Besides syntax, there's a logical difference between using unset() and assigning '' to the element.除了语法之外,使用unset()和将 '' 分配给元素之间存在逻辑差异。 The first says This doesn't exist anymore, while the second says This still exists, but its value is the empty string.第一个说This doesn't exist anymore,而第二个说This still exists, but its value is the empty string.

If you're dealing with numbers, assigning 0 may be a better alternative.如果您正在处理数字,分配 0 可能是更好的选择。 So, if a company stopped production of the model XL1000 sprocket, it would update its inventory with:因此,如果一家公司停止生产 XL1000 型链轮,它将更新其库存:

unset($products['XL1000']);

However, if it temporarily ran out of XL1000 sprockets, but was planning to receive a new shipment from the plant later this week, this is better:但是,如果它暂时用完了 XL1000 链轮,但计划在本周晚些时候从工厂接收新货物,则更好:

$products['XL1000'] = 0;

If you unset() an element, PHP adjusts the array so that looping still works correctly.如果您unset()一个元素,PHP 会调整数组,以便循环仍然正常工作。 It doesn't compact the array to fill in the missing holes.它不会压缩数组以填充缺失的孔。 This is what we mean when we say that all arrays are associative, even when they appear to be numeric.这就是我们所说的所有数组都是关联的,即使它们看起来是数字的。 Here's an example:下面是一个例子:

// 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

To compact the array into a densely filled numeric array, use array_values() :要将数组压缩为密集填充的数字数组,请使用array_values()

$animals = array_values($animals);

Alternatively, array_splice() automatically reindexes arrays to avoid leaving holes:或者, 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
)

This is useful if you're using the array as a queue and want to remove items from the queue while still allowing random access.如果您将数组用作队列并希望从队列中删除项目同时仍允许随机访问,这将非常有用。 To safely remove the first or last element from an array, use array_shift() and array_pop() , respectively.要安全地从数组中删除第一个或最后一个元素,请分别使用array_shift()array_pop()

Follow the default functions:遵循默认功能:

  • PHP: unset PHP:未设置

unset() destroys the specified variables. unset()销毁指定的变量。 For more info, you can refer to PHP unset有关更多信息,您可以参考PHP unset

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

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

The array_pop() function deletes the last element of an array. array_pop()函数删除数组的最后一个元素。 For more info, you can refer to PHP array_pop更多信息可以参考PHP array_pop

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

array_pop($Array);
  • PHP: array_splice PHP:array_splice

The array_splice() function removes selected elements from an array and replaces it with new elements. array_splice()函数从数组中删除选定的元素并用新元素替换它。 For more info, you can refer to PHP array_splice更多信息可以参考PHP array_splice

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

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

The array_shift() function removes the first element from an array. array_shift()函数从数组中删除第一个元素。 For more info, you can refer to PHP array_shift有关更多信息,您可以参考PHP array_shift

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

array_shift($Array);

Use array_search to get the key and remove it with unset if found:使用 array_search 获取密钥并在找到时使用 unset 将其删除:

if (($key = array_search('word', $array)) !== false) {
    unset($array[$key]);
}

I'd just like to say I had a particular object that had variable attributes (it was basically mapping a table and I was changing the columns in the table, so the attributes in the object, reflecting the table would vary as well):我只想说我有一个具有可变属性的特定对象(它基本上是映射表,我正在更改表中的列,因此对象中的属性,反映表也会有所不同):

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 {}
        }
    }
}

The whole purpose of $fields was just, so I don't have to look everywhere in the code when they're changed, I just look at the beginning of the class and change the list of attributes and the $fields array content to reflect the new attributes. $fields的全部目的只是,所以当它们改变时我不必在代码中到处查看,我只需查看类的开头并更改属性列表和$fields数组内容以反映新属性。

Suppose you have the following array:假设您有以下数组:

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

To delete storage , do:要删除storage ,请执行以下操作:

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

And you get:你会得到:

Array
(
    [user_id] => 193
)
<?php
    $array = array("your array");
    $array = array_diff($array, ["element you want to delete"]);
?>

Create your array in the variable $array and then where I have put 'element you want to delete' you put something like: "a".在变量$array创建$array ,然后在我放置“要删除的元素”的位置放置类似“a”的内容。 And if you want to delete multiple items then: "a", "b".如果您想删除多个项目,则:“a”、“b”。

Two ways for removing the first item of an array with keeping order of the index and also if you don't know the key name of the first item.在保持索引顺序的情况下删除数组的第一项的两种方法,以及如果您不知道第一项的键名。

Solution #1解决方案#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);

Solution #2解决方案#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]);

For this sample data:对于此示例数据:

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

You must have this result:你必须有这样的结果:

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

unset() multiple, fragmented elements from an array unset() 来自数组的多个碎片元素

While unset() has been mentioned here several times, it has yet to be mentioned that unset() accepts multiple variables making it easy to delete multiple, noncontiguous elements from an array in one operation:虽然这里多次提到unset() ,但尚未提及unset()接受多个变量,从而可以轻松地在一次操作中从数组中删除多个不连续的元素:

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

unset() dynamically动态取消设置()

unset() does not accept an array of keys to remove, so the code below will fail (it would have made it slightly easier to use unset() dynamically though). unset() 不接受要删除的键数组,因此下面的代码将失败(尽管它会使动态使用 unset() 稍微容易一些)。

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

Instead, unset() can be used dynamically in a foreach loop:相反, unset() 可以在 foreach 循环中动态使用:

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

Remove array keys by copying the array通过复制数组来删除数组键

There is also another practice that has yet to be mentioned.还有另一种做法尚未提及。 Sometimes, the simplest way to get rid of certain array keys is to simply copy $array1 into $array2.有时,摆脱某些数组键的最简单方法是简单地将 $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 ];

Obviously, the same practice applies to text strings:显然,同样的做法适用于文本字符串:

$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' ]

Remove an array element based on a key:根据键删除数组元素:

Use the unset function like below:使用如下所示的unset函数:

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

unset($a[1]);

print_r($a);

/*

    Output:

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

*/

Remove an array element based on value:根据值删除数组元素:

Use the array_search function to get an element key and use the above manner to remove an array element like below:使用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
        )

*/

Use the following code:使用以下代码:

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

Output输出

 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 )

For associative arrays, with non-integer keys:对于关联数组,使用非整数键:

Simply, unset($array[$key]) would work.简单地说, unset($array[$key])会起作用。

For arrays having integer keys and if you want to maintain your keys:对于具有整数键的数组,如果你想维护你的键:

  1. $array = [ 'mango', 'red', 'orange', 'grapes'];

     unset($array[2]); $array = array_values($array);
  2. array_splice($array, 2, 1);

$arrayName = array( '1' => 'somevalue',
                    '2' => 'somevalue1',
                    '3' => 'somevalue3',
                  );

print_r($arrayName[1]);
// somevalue
unset($arrayName[1]);

print_r($arrayName);

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?有没有一种简单的方法可以使用 PHP 从数组中删除元素,这样foreach ($array)不再包含该元素?

I thought that setting it to null would do it, but apparently it does not work.我认为将其设置为null会做到这一点,但显然它不起作用。

Edit编辑

If you can't take it as given that the object is in that array you need to add a check:如果您不能认为对象在该数组中,则需要添加检查:

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

Original Answer原答案

if you want to remove a specific object of an array by reference of that object you can do following:如果您想通过引用该对象来删除数组的特定对象,您可以执行以下操作:

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

Example:例子:

<?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>';
?>

Result:结果:

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"
    }
}

Note that if the object occures several times it will only be removed the first occurence!请注意,如果对象出现多次,它只会在第一次出现时被删除!

unset doesn't change the index, but array_splice does: unset不会更改索引,但是array_splice可以:

$arrayName = array('1' => 'somevalue',
                   '2' => 'somevalue1',
                   '3' => 'somevalue3',
                   500 => 'somevalue500',
                  );


    echo $arrayName['500'];
    //somevalue500
    array_splice($arrayName, 1, 2);

    print_r($arrayName);
    //Array ( [0] => somevalue [1] => somevalue500 )


    $arrayName = array( '1' => 'somevalue',
                        '2' => 'somevalue1',
                        '3' => 'somevalue3',
                        500 => 'somevalue500',
                      );


    echo $arrayName['500'];
    //somevalue500
    unset($arrayName[1]);

    print_r($arrayName);
    //Array ( [0] => somevalue [1] => somevalue500 )

I came here because I wanted to see if there was a more elegant solution to this problem than using unset($arr[$i]).我来这里是因为我想看看这个问题是否有比使用 unset($arr[$i]) 更优雅的解决方案。 To my disappointment these answers are either wrong or do not cover every edge case.令我失望的是,这些答案要么是错误的,要么没有涵盖所有边缘情况。

Here is why array_diff() does not work.这就是 array_diff() 不起作用的原因。 Keys are unique in the array, while elements are not always unique.键在数组中是唯一的,而元素并不总是唯一的。

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

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

Results...结果...

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

If two elements are the same they will be remove.如果两个元素相同,它们将被删除。 This also applies for array_search() and array_flip().这也适用于 array_search() 和 array_flip()。

I saw a lot of answers with array_slice() and array_splice(), but these functions only work with numeric arrays.我看到很多关于 array_slice() 和 array_splice() 的答案,但这些函数只适用于数值数组。 All the answers I am aware if here does not answer the question, and so here is a solution that will work.如果这里没有回答问题,我知道的所有答案,所以这里有一个可行的解决方案。

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

Since unset($arr[$i]) will work on both associative array and numeric arrays this still does not answer the question.由于 unset($arr[$i]) 将适用于关联数组和数字数组,因此这仍然不能回答问题。

This solution is to compare the keys and with a tool that will handle both numeric and associative arrays.此解决方案是将键与可处理数字和关联数组的工具进行比较。 I use array_diff_uassoc() for this.我为此使用了 array_diff_uassoc()。 This function compares the keys in a call back function.此函数比较回调函数中的键。

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

Results.....结果.....

[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'];

Step one firt of all start with php syntex第一步首先从 php syntex 开始

<?php

Step Two第二步

create an array named animals创建一个名为动物的数组

<?php 
$animals= array(
  
    'cat', // [0]
    'dog', // [1]
    'cow' // [2]
  
);

Step three第三步

remove item at index 1 which is 'for'删除索引 1 处的项目,即“for”

unset($animals1[1]); 

Step four第四步

Print modified array打印修改后的数组

var_dump($danimals1);

Step five第五步

Re-index the array elements重新索引数组元素

$newarray = array_values($animals1);
  

Step six第六步

Print re-indexed array打印重新索引的数组

var_dump($newarray);

Step seven第七步

Close php code关闭 php 代码

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM