在 PHP 中从数组中删除元素

发布于 2024-07-09 15:43:48 字数 115 浏览 7 评论 0 原文

有没有一种简单的方法可以使用 PHP 从数组中删除元素,使得 foreach ($array) 不再包含该元素?

我认为将其设置为 null 就可以了,但显然它不起作用。

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?

I thought that setting it to null would do it, but apparently it does not work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(27

渔村楼浪 2024-07-16 15:43:48

删除数组元素的方法有多种,其中某些方法对于某些特定任务比其他方法更有用。

删除单个数组元素

如果您只想删除一个数组元素,您可以使用 < code>unset() 或者 array_splice()

按键还是按值?

如果您知道该值但不知道删除该元素的键,您可以使用 array_search() 获取密钥。
仅当元素出现次数不超过一次时,此方法才有效,因为 array_search() 仅返回第一次匹配。

unset() 表达式

注意:当您使用 < code>unset() 数组键不会改变。
如果您想重新索引键,可以使用 array_values()unset() 之后,
它将所有键转换为从 0 开始的数字枚举键
(该数组仍然是一个列表)。

示例代码:

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

示例输出:

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

array_splice() 功能

如果您使用array_splice(),(整数)键将自动重新索引,
但关联(字符串)键不会改变 - 与 unset() 之后的 array_values() 相反,
这会将所有键转换为数字键。

注意:array_splice()
需要偏移量,而不是作为第二个参数; 偏移 = array_flip(array_keys(数组))[key]

示例代码:

$array = [0 => "a", 1 => "b", 2 => "c"];
array_splice($array, 1, 1);
                  // ↑ Offset of element 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 to delete

示例输出:

[
    [1] => b
]

array_diff_key()< /a> 函数

如果您知道要删除的元素的键,那么您需要使用array_diff_key()
您必须确保将键作为第二个参数中的键而不是值传递。
键不会重新索引。

示例代码:

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

示例输出:

[
    [1] => b
]

如果您想使用 unset()array_splice() 删除具有相同值的多个元素,您可以使用
array_keys() 获取所有密钥对于特定值
然后删除所有元素。

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
    [2] => c
]

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 single array element you can use unset() and alternatively array_splice().

By key or by value?

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 doesn't occur more than once, since array_search() returns the first hit only.

unset() Expression

Note: 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
(the array remains a list).

Example Code:

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

Example Output:

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

array_splice() Function

If you use array_splice() the (integer) keys will automatically be reindex-ed,
but the associative (string) keys won't change — as opposed to array_values() after unset(),
which will convert all keys to numerical keys.

Note: array_splice()
needs the offset, not the key, as the second parameter; offset = array_flip(array_keys(array))[key].

Example Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
array_splice($array, 1, 1);
                  // ↑ Offset of element to delete

Example Output:

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

array_splice(), same as unset(), take the array by reference. You don’t assign the return values 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 to remove from the array.

array_diff() Function

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.

Example Code:

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

Example Output:

[
    [1] => b
]

array_diff_key() Function

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.

Example Code:

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

Example 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() Function

If you want to delete all elements with a specific value in the array you can use array_filter().

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

Example Output:

[
    [0] => a
    [2] => c
]
别忘他 2024-07-16 15:43:48

应该注意的是 unset() 将保持索引不变,这就是你的d 期望使用字符串索引(数组作为哈希表),但在处理整数索引数组时可能会非常令人惊讶:

$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_splice如果您想规范化整数键,可以使用 ()。 另一种选择是在 array_values() .net/unset" rel="noreferrer">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)
} */

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)
} */
独自←快乐 2024-07-16 15:43:48
  // 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
)
  // 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. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use 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
)
辞取 2024-07-16 15:43:48
$key = array_search($needle, $array);
if ($key !== false) {
    unset($array[$key]);
}
$key = array_search($needle, $array);
if ($key !== false) {
    unset($array[$key]);
}
音盲 2024-07-16 15:43:48
unset($array[$index]);
unset($array[$index]);
夜司空 2024-07-16 15:43:48

另外,对于命名元素:

unset($array["elementName"]);

Also, for a named element:

unset($array["elementName"]);
无声无音无过去 2024-07-16 15:43:48

如果您有一个数字索引数组,其中所有值都是唯一的(或者它们不是唯一的,但您希望删除特定值的所有实例),则可以简单地使用 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”的元素被删除,这可以通过 sizeof() 调用进行验证,该调用报告初始数组的大小为 4,删除后为 3。

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:

$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.

剪不断理还乱 2024-07-16 15:43:48

销毁数组的单个元素

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

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
时光与爱终年不遇 2024-07-16 15:43:48
<?php
    $stack = ["fruit1", "fruit2", "fruit3", "fruit4"];
    $fruit = array_shift($stack);
    print_r($stack);

    echo $fruit;
?>

输出:

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

fruit1
<?php
    $stack = ["fruit1", "fruit2", "fruit3", "fruit4"];
    $fruit = array_shift($stack);
    print_r($stack);

    echo $fruit;
?>

Output:

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

fruit1
违心° 2024-07-16 15:43:48

如果指定了索引:

$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()会自动删除
数组的第一个元素!!! 这不是我们想要的。

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.

二智少女猫性小仙女 2024-07-16 15:43:48

如果您必须删除数组中的多个值,并且该数组中的条目是对象或结构化数据,array_filter()< /code> 是你最好的选择。 那些从回调函数返回 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']]

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. Those entries that return a true from the callback function will be retained.

$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']]
黑色毁心梦 2024-07-16 15:43:48

如果需要从关联数组中删除多个元素,可以使用 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 ) 

If you need to remove multiple elements from an associative array, you can use array_diff_key() (here used with 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 ) 
把人绕傻吧 2024-07-16 15:43:48

关联数组

对于关联数组,请使用 unset

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

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

数字数组

对于数字数组,请使用 array_splice

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

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

注意

使用unset 对于数字数组不会产生错误,但它会弄乱你的索引:

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

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

Associative arrays

For associative arrays, use 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:

$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:

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

// RESULT: array(0 => 1, 2 => 3)
毁我热情 2024-07-16 15:43:48

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

unset() destroys the specified variables.

The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.

If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

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

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

The answer of the above code will be bar.

To unset() a global variable inside of a function:

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

    $bar = "something";
    foo();
?>
扛刀软妹 2024-07-16 15:43:48
// Remove by value
function removeFromArr($arr, $val)
{
    unset($arr[array_search($val, $arr)]);
    return array_values($arr);
}
// Remove by value
function removeFromArr($arr, $val)
{
    unset($arr[array_search($val, $arr)]);
    return array_values($arr);
}
饮湿 2024-07-16 15:43:48

解决方案:

  1. 要删除一个元素,请使用 unset()
unset($array[3]); 
  取消设置($array['foo']); 
  
  1. 要删除多个不连续的元素,还可以使用 unset()
unset($array[3], $array[5]); 
  取消设置($array['foo'], $array['bar']); 
  
  1. 要删除多个连续元素,请使用 array_splice()
array_splice($array, $offset, $length); 
  

进一步说明:

使用这些函数将从 PHP 中删除对这些元素的所有引用。 如果您想在数组中保留一个键,但值为空,请将空字符串分配给该元素:

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

除了语法之外,使用 unset() 并将 '' 分配给该元素。 第一个表示 This 不再存在, 而第二个表示 This 仍然存在,但其值为空字符串。

如果您正在处理数字,请分配 0可能是一个更好的选择。 因此,如果一家公司停止生产 XL1000 型链轮,它将更新其库存:

unset($products['XL1000']);

但是,如果暂时用完 XL1000 链轮,但计划在本周晚些时候从工厂收到新的货物,则更好:

$products['XL1000'] = 0;

如果您 unset() 一个元素,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() 分别。

Solutions:

  1. To delete one element, use unset():
unset($array[3]);
unset($array['foo']);
  1. To delete multiple noncontiguous elements, also use unset():
unset($array[3], $array[5]);
unset($array['foo'], $array['bar']);
  1. To delete multiple contiguous elements, use array_splice():
array_splice($array, $offset, $length);

Further explanation:

Using these functions removes all references to these elements from 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. The first says This doesn't exist anymore, while the second says This still exists, but its value is the empty string.

If you're dealing with numbers, assigning 0 may be a better alternative. So, if a company stopped production of the model XL1000 sprocket, it would update its inventory with:

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:

$products['XL1000'] = 0;

If you unset() an element, PHP adjusts the array so that looping still works correctly. 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():

$animals = array_values($animals);

Alternatively, array_splice() automatically reindexes arrays to avoid leaving holes:

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

天暗了我发光 2024-07-16 15:43:48

遵循默认函数:

  • PHP: unset

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

Follow the default functions:

  • PHP: unset

unset() destroys the specified variables. For more info, you can refer to PHP unset

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

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

The array_pop() function deletes the last element of an array. For more info, you can refer to PHP array_pop

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

array_pop($Array);
  • PHP: array_splice

The array_splice() function removes selected elements from an array and replaces it with new elements. For more info, you can refer to PHP array_splice

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

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

The array_shift() function removes the first element from an array. For more info, you can refer to PHP array_shift

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

array_shift($Array);
jJeQQOZ5 2024-07-16 15:43:48

我只想说我有一个具有可变属性的特定对象(它基本上是映射一个表,并且我正在更改表中的列,因此反映表的对象中的属性也会有所不同)

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 数组内容以反映新属性。

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.

長街聽風 2024-07-16 15:43:48

删除数组的第一项并保持索引顺序的两种方法以及如果您不知道第一项的键名称的情况。

解决方案 #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"
}

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

// 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"
}
ぺ禁宫浮华殁 2024-07-16 15:43:48

编辑

如果您不能认为该对象位于该数组中,则需要添加检查:

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

请注意,如果该对象出现多次,则只会删除第一次出现的对象!

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!

心头的小情儿 2024-07-16 15:43:48

unset() 来自数组的多个碎片元素

虽然这里多次提到了 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() 动态

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() multiple, fragmented elements from an array

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:

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

$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:

$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 = 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' ]
南渊 2024-07-16 15:43:48
<?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 )
<?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 )
£冰雨忧蓝° 2024-07-16 15:43:48

根据键删除数组元素:

使用 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
        )

*/

Remove an array element based on a key:

Use the unset function like below:

$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:

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

*/
赤濁 2024-07-16 15:43:48

使用以下代码:

$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);

Use the following code:

$arr = array('orange', 'banana', 'apple', 'raspberry');
$result = array_pop($arr);
print_r($result);
茶花眉 2024-07-16 15:43:48

要从 PHP 数组中删除元素,使其不再包含在 foreach 循环中,您可以使用多种方法。 这是一个简单的方法:

方法:使用 unset()

  • 用法:非常适合在知道元素键时删除元素。
  • 行为:不重新索引数字数组键。
  • 示例
    $myArray = ['苹果', '香蕉', '樱桃']; 
      取消设置($myArray[1]);   // 删除“香蕉” 
      

方法:使用array_splice()

  • 用法:当您想要根据元素的位置(偏移量)删除元素并自动重新索引数字键时很有用。
  • 示例
    $myArray = ['苹果', '香蕉', '樱桃']; 
      array_splice($myArray, 1, 1);   // 删除“香蕉” 
      

方法:使用array_diff()

  • 用法:适合通过值删除元素。 不影响按键。
  • 示例
    $myArray = ['苹果', '香蕉', '樱桃']; 
      $myArray = array_diff($myArray, ['香蕉']);   // 删除“香蕉” 
      

方法:使用array_filter()

  • 用法:最适合根据条件删除元素。
  • 示例
    $myArray = ['苹果', '香蕉', '樱桃']; 
      $myArray = array_filter($myArray, 函数($item) { 
          return $item !== '香蕉'; 
      }); 
      

这些方法中的每一种都有其特定的用例和对数组结构的影响,尤其是在键方面。 选择最适合您需要的一种。

有关 PHP 中数组操作的更全面的见解和高级示例,您可能会找到这个文章有帮助。

To remove an element from an array in PHP so it's no longer included in a foreach loop, you can use several methods. Here's a straightforward approach:

Method: Using unset()

  • Usage: Ideal for removing an element when you know its key.
  • Behavior: Does not reindex numeric array keys.
  • Example:
    $myArray = ['apple', 'banana', 'cherry'];
    unset($myArray[1]); // Removes 'banana'
    

Method: Using array_splice()

  • Usage: Useful when you want to remove an element based on its position (offset) and automatically reindex numeric keys.
  • Example:
    $myArray = ['apple', 'banana', 'cherry'];
    array_splice($myArray, 1, 1); // Removes 'banana'
    

Method: Using array_diff()

  • Usage: Suitable for removing elements by their values. Does not affect keys.
  • Example:
    $myArray = ['apple', 'banana', 'cherry'];
    $myArray = array_diff($myArray, ['banana']); // Removes 'banana'
    

Method: Using array_filter()

  • Usage: Best for removing elements based on a condition.
  • Example:
    $myArray = ['apple', 'banana', 'cherry'];
    $myArray = array_filter($myArray, function($item) {
        return $item !== 'banana';
    });
    

Each of these methods has its specific use cases and effects on the array structure, especially regarding keys. Choose the one that best suits your need.

For more comprehensive insights and advanced examples on array manipulation in PHP, you might find this article helpful.

过期以后 2024-07-16 15:43:48

我来这里是因为我想看看是否有比使用 unset($arr[$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($arr[$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'];

I came here because I wanted to see if there was a more elegant solution to this problem than using 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. 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().

I saw a lot of answers with array_slice() and array_splice(), but these functions only work with numeric arrays. 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.

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. 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'];
情释 2024-07-16 15:43:48

删除单个数组元素

如果您只想删除一个数组元素,您可以使用 unset()array_splice()

Deleting a Single Array Element

If you want to delete just one single array element you can use unset() and alternatively array_splice().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文