PHP:如何从数组中删除特定的元素?

时间:2021-06-04 13:38:30

How do I remove an element from an array when I know the elements name? for example:

当我知道元素名称时,如何从数组中删除元素?例如:

I have an array:

我有一个数组:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');

the user enters strawberry

用户输入草莓

strawberry is removed.

草莓被移除。

To fully explain:

完全解释:

I have a database that stores a list of items separated by a comma. The code pulls in the list based on a user choice where that choice is located. So, if they choose strawberry they code pulls in every entry were strawberry is located then converts that to an array using split(). I want to them remove the user chosen items, for this example strawberry, from the array.

我有一个数据库,它存储用逗号分隔的项目列表。代码根据用户的选择来获取列表。所以,如果他们选择了草莓,他们会在每个条目中加入草莓,然后使用split()将其转换为数组。我想让它们从数组中删除用户选择的项,例如草莓。

19 个解决方案

#1


224  

Use array_search to get the key and remove it with unset if found:

使用array_search获取密钥并在未设置的情况下将其删除:

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

array_search returns false (null until PHP 4.2.0) if no item has been found.

如果没有找到任何项,array_search将返回false (null,直到PHP 4.2.0)。

And if there can be multiple items with the same value, you can use array_keys to get the keys to all items:

如果有多个项目具有相同的值,可以使用array_keys获取所有项目的键:

foreach (array_keys($array, 'strawberry') as $key) {
    unset($array[$key]);
}

#2


98  

Use array_diff() for 1 line solution:

对一行解决方案使用array_diff():

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi', 'strawberry'); //throw in another 'strawberry' to demonstrate that it removes multiple instances of the string
$array_without_strawberries = array_diff($array, array('strawberry'));
print_r($array_without_strawberries);

...No need for extra functions or foreach loop.

…不需要额外的函数或foreach循环。

#3


33  

if (in_array('strawberry', $array)) 
{
    unset($array[array_search('strawberry',$array)]);
}

#4


16  

If you are using a plain array here (which seems like the case), you should be using this code instead:

如果您在这里使用的是一个普通数组(看起来是这样的),那么您应该使用以下代码:

if (($key = array_search('strawberry', $array)) !== false) {
    array_splice($array, $key, 1);
}

unset($array[$key]) only removes the element but does not reorder the plain array.

unset($array[$key])只删除元素,不重新排序普通数组。

Supposingly we have an array and use array_splice:

假设我们有一个数组并使用array_splice:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
array_splice($array, 2, 1);
json_encode($array); 
// yields the array ['apple', 'orange', 'blueberry', 'kiwi']

Compared to unset:

与设置:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[2]);
json_encode($array);
// yields an object {"0": "apple", "1": "orange", "3": "blueberry", "4": "kiwi"}

Notice how unset($array[$key]) does not reorder the array.

注意未设置($array[$key])如何不重新排序数组。

#5


7  

$arr = \array_filter($arr, function ($v) { return $v != 'some_value'; }

$arr = \array_filter($arr, function ($v) {return $v != 'some_value';}

#6


4  

This is a simple reiteration that can delete multiple values in the array.

这是一个简单的重复操作,可以删除数组中的多个值。

    // Your array
    $list = array("apple", "orange", "strawberry", "lemon", "banana");

    // Initilize what to delete
    $delete_val = array("orange", "lemon", "banana");

    // Search for the array key and unset   
    foreach($delete_val as $key){
        $keyToDelete = array_search($key, $list);
        unset($list[$keyToDelete]);
    }

#7


3  

I'm currently using this function:

我目前正在使用这个功能:

function array_delete($del_val, $array) {
    if(is_array($del_val)) {
         foreach ($del_val as $del_key => $del_value) {
            foreach ($array as $key => $value){
                if ($value == $del_value) {
                    unset($array[$key]);
                }
            }
        }
    } else {
        foreach ($array as $key => $value){
            if ($value == $del_val) {
                unset($array[$key]);
            }
        }
    }
    return array_values($array);
}

You can input an array or only a string with the element(s) which should be removed. Write it like this:

您可以输入一个数组,或者只有一个带元素(s)的字符串,该元素应该被删除。这样写:

$detils = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$detils = array_delete(array('orange', 'apple'), $detils);

OR

$detils = array_delete('orange', $detils);

$ detils = array_delete(“橙色”,detils美元);

It'll also reindex it.

它还将重建索引。

#8


2  

Will be like this:

将是这样的:

 function rmv_val($var)
 {
     return(!($var == 'strawberry'));
 }

 $array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');

 $array_res = array_filter($array, "rmv_val");

#9


1  

A better approach would maybe be to keep your values as keys in an associative array, and then call array_keys() on it when you want to actual array. That way you don't need to use array_search to find your element.

更好的方法可能是将值作为键保存在关联数组中,然后在需要实际数组时调用array_keys()。这样就不需要使用array_search来查找元素。

#10


0  

I would prefer to use array_key_exists to search for keys in arrays like:

我更喜欢使用array_key_exist搜索数组中的键,如:

Array([0]=>'A',[1]=>'B',['key'=>'value'])

阵列([0]= > ' A ',[1]= >“B”,(“关键”= >“价值”))

to find the specified effectively, since array_search and in_array() don't work here. And do removing stuff with unset().

要有效地找到指定的值,array_search和in_array()在这里不起作用。并使用unset()删除内容。

I think it will help someone.

我认为这对某人有帮助。

#11


0  

Create numeric array with delete particular Array value

    <?php
    // create a "numeric" array
    $animals = array('monitor', 'cpu', 'mouse', 'ram', 'wifi', 'usb', 'pendrive');

    //Normarl display
    print_r($animals);
    echo "<br/><br/>";

    //If splice the array
    //array_splice($animals, 2, 2);
    unset($animals[3]); // you can unset the particular value
    print_r($animals);

    ?>

You Can Refer this link..

你可以参考这个链接。

#12


0  

The answer to PHP array delete by value (not key) Given by https://*.com/users/924109/rok-kralj

PHP数组删除的答案(不是键)由https://*.com/users/924109/rok-kralj给出

IMO is the best answer as it removes and does not mutate

IMO是最好的答案,因为它可以去除并且不会变异

array_diff( [312, 401, 15, 401, 3], [401] ) // removing 401 returns [312, 15, 3]

It generalizes nicely, you can remove as many elements as you like at the same time, if you want.

它很好地概括了,您可以同时删除任意多的元素,如果您愿意的话。

Disclaimer: Note that my solution produces a new copy of the array while keeping the old one intact in contrast to the accepted answer which mutates. It might be a bit slower because of this.

免责声明:注意,我的解决方案生成一个新的数组副本,同时保持旧的数组的完整,而不是与已接受的答案发生突变。因为这个原因,它可能会慢一点。

#13


0  

$remove= "strawberry";
$array = ["apple", "orange", "strawberry", "blueberry", "kiwi"];
foreach ($array as $key => $value) {
        if ($value!=$remove) {
        echo $value.'<br/>';
                continue;
        }
}

#14


0  

<?php 
$array = array("apple", "orange", "strawberry", "blueberry", "kiwi");
$delete = "strawberry";
$index = array_search($delete, $array);
array_splice($array, $index, 1);
var_dump($array);
?>

#15


0  

This question has several answers but I want to add something more because when I used unset or array_diff I had several problems to play with the indexes of the new array when the specific element was removed (because the initial index are saved)

这个问题有几个答案,但我想添加更多的东西,因为当我使用unset或array_diff时,当删除特定元素时,我有几个问题需要处理新数组的索引(因为初始索引保存了)

I get back to the example :

我回到这个例子:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$array_without_strawberries = array_diff($array, array('strawberry'));

or

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[array_search('strawberry', $array)]);

If you print the result you will obtain :

如你列印你将会得到的结果:

foreach ($array_without_strawberries as $data) {
   print_r($data);
}

Result :

结果:

> apple
> orange
> blueberry
> kiwi

But the indexes will be saved and so you will access to your element like :

但是索引将被保存,因此您将访问您的元素,如:

$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[3] > blueberry
$array_without_strawberries[4] > kiwi

And so the final array are not re-indexed. So you need to add after the unset or array_diff:

最后一个数组没有被重新编入索引。所以你需要添加unset或array_diff:

$array_without_strawberries = array_values($array);

After that your array will have a normal index :

之后你的数组将有一个正常的索引:

$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[2] > blueberry
$array_without_strawberries[3] > kiwi

Related to this post : Re-Index Array

与本文相关:重新索引数组

PHP:如何从数组中删除特定的元素?

Hope it will help

希望它能帮助

#16


-1  

Using array_seach(), try the following:

使用array_seach(),尝试以下操作:

if(($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
}

array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a "falsey" value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.

array_search()返回它找到的元素的键,可以使用unset()从原始数组中删除该元素。它将在失败时返回FALSE,但是在成功时返回“falsey”值(例如,您的键可能是0),这就是为什么使用严格的compare !=操作符。

The if() statement will check whether array_search() returned a value, and will only perform an action if it did.

if()语句将检查array_search()是否返回一个值,并且只在返回值时执行操作。

#17


-1  

unset($array[array_search('strawberry', $array)]);

#18


-1  

$delete = "strawberry";

$删除=“草莓”;

$index = array_search($delete, $array);

函数的作用是美元指数=(删除数组美元);

array_splice($array, $index, 1);

作用是数组,美元指数,1);

#19


-2  

$detils = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
     function remove_embpty($values)
     {
        if($values=='orange')
        {
            $values='any name';
        }
        return $values;
     }
     $detils=array_map('remove_embpty',$detils);
    print_r($detils);

#1


224  

Use array_search to get the key and remove it with unset if found:

使用array_search获取密钥并在未设置的情况下将其删除:

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

array_search returns false (null until PHP 4.2.0) if no item has been found.

如果没有找到任何项,array_search将返回false (null,直到PHP 4.2.0)。

And if there can be multiple items with the same value, you can use array_keys to get the keys to all items:

如果有多个项目具有相同的值,可以使用array_keys获取所有项目的键:

foreach (array_keys($array, 'strawberry') as $key) {
    unset($array[$key]);
}

#2


98  

Use array_diff() for 1 line solution:

对一行解决方案使用array_diff():

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi', 'strawberry'); //throw in another 'strawberry' to demonstrate that it removes multiple instances of the string
$array_without_strawberries = array_diff($array, array('strawberry'));
print_r($array_without_strawberries);

...No need for extra functions or foreach loop.

…不需要额外的函数或foreach循环。

#3


33  

if (in_array('strawberry', $array)) 
{
    unset($array[array_search('strawberry',$array)]);
}

#4


16  

If you are using a plain array here (which seems like the case), you should be using this code instead:

如果您在这里使用的是一个普通数组(看起来是这样的),那么您应该使用以下代码:

if (($key = array_search('strawberry', $array)) !== false) {
    array_splice($array, $key, 1);
}

unset($array[$key]) only removes the element but does not reorder the plain array.

unset($array[$key])只删除元素,不重新排序普通数组。

Supposingly we have an array and use array_splice:

假设我们有一个数组并使用array_splice:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
array_splice($array, 2, 1);
json_encode($array); 
// yields the array ['apple', 'orange', 'blueberry', 'kiwi']

Compared to unset:

与设置:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[2]);
json_encode($array);
// yields an object {"0": "apple", "1": "orange", "3": "blueberry", "4": "kiwi"}

Notice how unset($array[$key]) does not reorder the array.

注意未设置($array[$key])如何不重新排序数组。

#5


7  

$arr = \array_filter($arr, function ($v) { return $v != 'some_value'; }

$arr = \array_filter($arr, function ($v) {return $v != 'some_value';}

#6


4  

This is a simple reiteration that can delete multiple values in the array.

这是一个简单的重复操作,可以删除数组中的多个值。

    // Your array
    $list = array("apple", "orange", "strawberry", "lemon", "banana");

    // Initilize what to delete
    $delete_val = array("orange", "lemon", "banana");

    // Search for the array key and unset   
    foreach($delete_val as $key){
        $keyToDelete = array_search($key, $list);
        unset($list[$keyToDelete]);
    }

#7


3  

I'm currently using this function:

我目前正在使用这个功能:

function array_delete($del_val, $array) {
    if(is_array($del_val)) {
         foreach ($del_val as $del_key => $del_value) {
            foreach ($array as $key => $value){
                if ($value == $del_value) {
                    unset($array[$key]);
                }
            }
        }
    } else {
        foreach ($array as $key => $value){
            if ($value == $del_val) {
                unset($array[$key]);
            }
        }
    }
    return array_values($array);
}

You can input an array or only a string with the element(s) which should be removed. Write it like this:

您可以输入一个数组,或者只有一个带元素(s)的字符串,该元素应该被删除。这样写:

$detils = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$detils = array_delete(array('orange', 'apple'), $detils);

OR

$detils = array_delete('orange', $detils);

$ detils = array_delete(“橙色”,detils美元);

It'll also reindex it.

它还将重建索引。

#8


2  

Will be like this:

将是这样的:

 function rmv_val($var)
 {
     return(!($var == 'strawberry'));
 }

 $array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');

 $array_res = array_filter($array, "rmv_val");

#9


1  

A better approach would maybe be to keep your values as keys in an associative array, and then call array_keys() on it when you want to actual array. That way you don't need to use array_search to find your element.

更好的方法可能是将值作为键保存在关联数组中,然后在需要实际数组时调用array_keys()。这样就不需要使用array_search来查找元素。

#10


0  

I would prefer to use array_key_exists to search for keys in arrays like:

我更喜欢使用array_key_exist搜索数组中的键,如:

Array([0]=>'A',[1]=>'B',['key'=>'value'])

阵列([0]= > ' A ',[1]= >“B”,(“关键”= >“价值”))

to find the specified effectively, since array_search and in_array() don't work here. And do removing stuff with unset().

要有效地找到指定的值,array_search和in_array()在这里不起作用。并使用unset()删除内容。

I think it will help someone.

我认为这对某人有帮助。

#11


0  

Create numeric array with delete particular Array value

    <?php
    // create a "numeric" array
    $animals = array('monitor', 'cpu', 'mouse', 'ram', 'wifi', 'usb', 'pendrive');

    //Normarl display
    print_r($animals);
    echo "<br/><br/>";

    //If splice the array
    //array_splice($animals, 2, 2);
    unset($animals[3]); // you can unset the particular value
    print_r($animals);

    ?>

You Can Refer this link..

你可以参考这个链接。

#12


0  

The answer to PHP array delete by value (not key) Given by https://*.com/users/924109/rok-kralj

PHP数组删除的答案(不是键)由https://*.com/users/924109/rok-kralj给出

IMO is the best answer as it removes and does not mutate

IMO是最好的答案,因为它可以去除并且不会变异

array_diff( [312, 401, 15, 401, 3], [401] ) // removing 401 returns [312, 15, 3]

It generalizes nicely, you can remove as many elements as you like at the same time, if you want.

它很好地概括了,您可以同时删除任意多的元素,如果您愿意的话。

Disclaimer: Note that my solution produces a new copy of the array while keeping the old one intact in contrast to the accepted answer which mutates. It might be a bit slower because of this.

免责声明:注意,我的解决方案生成一个新的数组副本,同时保持旧的数组的完整,而不是与已接受的答案发生突变。因为这个原因,它可能会慢一点。

#13


0  

$remove= "strawberry";
$array = ["apple", "orange", "strawberry", "blueberry", "kiwi"];
foreach ($array as $key => $value) {
        if ($value!=$remove) {
        echo $value.'<br/>';
                continue;
        }
}

#14


0  

<?php 
$array = array("apple", "orange", "strawberry", "blueberry", "kiwi");
$delete = "strawberry";
$index = array_search($delete, $array);
array_splice($array, $index, 1);
var_dump($array);
?>

#15


0  

This question has several answers but I want to add something more because when I used unset or array_diff I had several problems to play with the indexes of the new array when the specific element was removed (because the initial index are saved)

这个问题有几个答案,但我想添加更多的东西,因为当我使用unset或array_diff时,当删除特定元素时,我有几个问题需要处理新数组的索引(因为初始索引保存了)

I get back to the example :

我回到这个例子:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$array_without_strawberries = array_diff($array, array('strawberry'));

or

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[array_search('strawberry', $array)]);

If you print the result you will obtain :

如你列印你将会得到的结果:

foreach ($array_without_strawberries as $data) {
   print_r($data);
}

Result :

结果:

> apple
> orange
> blueberry
> kiwi

But the indexes will be saved and so you will access to your element like :

但是索引将被保存,因此您将访问您的元素,如:

$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[3] > blueberry
$array_without_strawberries[4] > kiwi

And so the final array are not re-indexed. So you need to add after the unset or array_diff:

最后一个数组没有被重新编入索引。所以你需要添加unset或array_diff:

$array_without_strawberries = array_values($array);

After that your array will have a normal index :

之后你的数组将有一个正常的索引:

$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[2] > blueberry
$array_without_strawberries[3] > kiwi

Related to this post : Re-Index Array

与本文相关:重新索引数组

PHP:如何从数组中删除特定的元素?

Hope it will help

希望它能帮助

#16


-1  

Using array_seach(), try the following:

使用array_seach(),尝试以下操作:

if(($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
}

array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a "falsey" value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.

array_search()返回它找到的元素的键,可以使用unset()从原始数组中删除该元素。它将在失败时返回FALSE,但是在成功时返回“falsey”值(例如,您的键可能是0),这就是为什么使用严格的compare !=操作符。

The if() statement will check whether array_search() returned a value, and will only perform an action if it did.

if()语句将检查array_search()是否返回一个值,并且只在返回值时执行操作。

#17


-1  

unset($array[array_search('strawberry', $array)]);

#18


-1  

$delete = "strawberry";

$删除=“草莓”;

$index = array_search($delete, $array);

函数的作用是美元指数=(删除数组美元);

array_splice($array, $index, 1);

作用是数组,美元指数,1);

#19


-2  

$detils = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
     function remove_embpty($values)
     {
        if($values=='orange')
        {
            $values='any name';
        }
        return $values;
     }
     $detils=array_map('remove_embpty',$detils);
    print_r($detils);