PHP数组按值删除(不是键)

时间:2021-11-20 21:30:48

I have a PHP array as follows:

我有一个PHP数组如下:

$messages = [312, 401, 1599, 3, ...];

I want to delete the element containing the value $del_val (for example, $del_val=401), but I don't know its key. This might help: each value can only be there once.

我想删除包含$del_val(例如$del_val=401)的元素,但是我不知道它的键。这可能会有帮助:每个值只能存在一次。

I'm looking for the simplest function to perform this task please.

我在寻找最简单的函数来执行这个任务。

25 个解决方案

#1


1182  

Using array_search() and unset, try the following:

使用array_search()和unset,尝试以下方法:

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 false-y value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.

array_search()返回它找到的元素的键,可以使用unset()来从原始数组中移除该元素。如果失败,它将返回FALSE,但是它可以返回一个错误的成功值(例如,您的键可能是0),这就是为什么要使用严格的比较!

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

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

#2


429  

Well, deleting an element from array is basically just set difference with one element.

从数组中删除一个元素基本上就是用一个元素来设置不同。

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.

免责声明:请注意,我的解决方案生成一个数组的新副本,同时保持旧的数组不变,而不与被接受的答案相冲突。可能会稍微慢一点。

#3


91  

One interesting way is by using array_keys():

一个有趣的方法是使用array_keys():

foreach (array_keys($messages, 401, true) as $key) {
    unset($messages[$key]);
}

The array_keys() function takes two additional parameters to return only keys for a particular value and whether strict checking is required (i.e. using === for comparison).

array_keys()函数使用两个额外的参数,只返回特定值的键,以及是否需要严格检查(例如,使用===进行比较)。

This can also remove multiple array items with the same value (e.g. [1, 2, 3, 3, 4]).

这还可以删除具有相同值的多个数组项(例如,[1,2,3,3,4])。

#4


40  

If you know for definite that your array will contain only one element with that value, you can do

如果您确定您的数组只包含一个具有该值的元素,您可以这样做。

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

If, however, your value might occur more than once in your array, you could do this

但是,如果您的值在数组中不止一次发生,您可以这样做。

$array = array_filter($array, function($e) use ($del_val) {
    return ($e !== $del_val);
});

Note: The second option only works for PHP5.3+ with Closures

注意:第二个选项只适用于使用闭包的PHP5.3+。

#5


34  

$fields = array_flip($fields);
unset($fields['myvalue']);
$fields = array_flip($fields);

#6


21  

Have a look at following code:

看看下面的代码:

$arr = array('nice_item', 'remove_me', 'another_liked_item', 'remove_me_also');

You can do:

你能做什么:

$arr = array_diff($arr, array('remove_me', 'remove_me_also'));

And that will get you this array:

这样就得到了这个数组

array('nice_item', 'another_liked_item')

#7


15  

Or simply, manual way:

或简单,手动方式:

foreach ($array as $key => $value){
    if ($value == $target_value) {
        unset($array[$key]);
    }
}

This is the safest of them because you have full control on your array

这是最安全的,因为您可以完全控制您的数组。

#8


15  

The Best way is array_splice

最好的方法是array_splice。

array_splice($array, array_search(58, $array ), 1);

Reason for Best is here at http://www.programmerinterview.com/index.php/php-questions/how-to-delete-an-element-from-an-array-in-php/

最好的原因是这里的http://www.programmerinterview.com/index.php/php/howto -delete-an- arrayin -php/。

#9


14  

By the following code, the repetitive values will be removed from the $messages.

通过下面的代码,将从$messages中删除重复的值。

$messages = array_diff($messages, array(401));

(消息= array_diff美元消息,阵列(401));

#10


9  

function array_remove_by_value($array, $value)
{
    return array_values(array_diff($array, array($value)));
}

$array = array(312, 401, 1599, 3);

$newarray = array_remove_by_value($array, 401);

print_r($newarray);

Output

输出

Array ( [0] => 312 [1] => 1599 [2] => 3 )

数组([0]=> 312 [1]=> 1599 [2]=> 3)

#11


7  

To delete multiple values try this one

要删除多个值,请尝试这个。

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

#12


7  

you can do:

你能做什么:

unset($messages[array_flip($messages)['401']]);

Explanation: Delete the element that has the key 401 after flipping the array.

说明:删除在翻转数组后拥有键401的元素。

#13


6  

If you have > php5.3, there is the one line code :

如果你有> php5.3,有一行代码:

$array = array_filter($array, function($i) use ($value){return $i != $value;}); 

#14


5  

Borrowed the logic of underscoreJS _.reject and created two functions (people prefer functions!!)

借用了underscoreJS的逻辑。拒绝和创建两个函数(人们喜欢函数!!)

array_reject_value: This function is simply rejecting the value specified (also works for PHP4,5,7)

array_reject_value:这个函数简单地拒绝指定的值(也适用于PHP4、5、7)

function array_reject_value(array &$arrayToFilter, $deleteValue) {
    $filteredArray = array();

    foreach ($arrayToFilter as $key => $value) {
        if ($value !== $deleteValue) {
            $filteredArray[] = $value;
        }
    }

    return $filteredArray;
}

array_reject: This function is simply rejecting the callable method (works for PHP >=5.3)

array_reject:这个函数简单地拒绝callable方法(用于PHP >=5.3)

function array_reject(array &$arrayToFilter, callable $rejectCallback) {

    $filteredArray = array();

    foreach ($arrayToFilter as $key => $value) {
        if (!$rejectCallback($value, $key)) {
            $filteredArray[] = $value;
        }
    }

    return $filteredArray;
}

So in our current example we can use the above functions as follows:

在我们当前的例子中,我们可以使用上面的函数如下:

$messages = [312, 401, 1599, 3, 6];
$messages = array_reject_value($messages, 401);

or even better: (as this give us a better syntax to use like the array_filter one)

或者更好:(因为这给了我们更好的语法,可以像array_filter一样使用)

$messages = [312, 401, 1599, 3, 6];
$messages = array_reject($messages, function ($value) {
    return $value === 401;
});

The above can be used for more complicated stuff like let's say we would like to remove all the values that are greater or equal to 401 we could simply do this:

上面可以用来做更复杂的事情比如我们想要移除所有大于或等于401的值我们可以这样做:

$messages = [312, 401, 1599, 3, 6];
$greaterOrEqualThan = 401;
$messages = array_reject($messages, function ($value) use $greaterOrEqualThan {
    return $value >= $greaterOrEqualThan;
});

#15


4  

Get the key with array_search().

使用array_search()获取密钥。

#16


4  

@Bojangles answer did help me. Thank you.

@Bojangles的回答确实帮助了我。谢谢你!

In my case, the array could be associative or not, so I added this function

在我的例子中,数组可以是关联的,也可以不是,所以我添加了这个函数。

function test($value, $tab) {

 if(($key = array_search($value, $tab)) !== false) {
    unset($tab[$key]); return true;

 } else if (array_key_exists($value, $tab)){
        unset($tab[$value]); return true;

 } else {
    return false; // the $value is not in the array $tab
 }

}

Regards

问候

#17


3  

If your values you want to delete are, or can, be in an array. Use the array_diff function. Seems to work great for things like this.

如果您想要删除的值是(或可以)在数组中。array_diff函数使用。似乎对这样的事情很有用。

array_diff

array_diff

$arrayWithValuesRemoved = array_diff($arrayOfData, $arrayOfValuesToRemove);

#18


3  

OK.. I know this is not efficient at all but is simple, intuitive and easy to read.
So if someone is looking for a not so fancy solution which can be extended to work with more values, or more specific conditions .. here is a simple code:

好吧. .我知道这一点都不高效,但简单、直观、易于阅读。因此,如果有人在寻找一个不那么奇特的解决方案,可以扩展到更有价值的工作,或者更具体的条件。这里有一个简单的代码:

$result = array();
$del_value = 401;
//$del_values = array(... all the values you don`t wont);

foreach($arr as $key =>$value){
    if ($value !== $del_value){
        $result[$key] = $value;
    }

    //if(!in_array($value, $del_values)){
    //    $result[$key] = $value;
    //}

    //if($this->validete($value)){
    //      $result[$key] = $value;
    //}
}

return $result

#19


3  

If you don't know its key it means it doesn't matter.

如果你不知道它的关键,那就意味着它无关紧要。

You could place the value as the key, it means it will instant find the value. Better than using searching in all elements over and over again.

您可以将该值作为键,这意味着它将立即找到该值。比在所有元素中反复搜索要好。

$messages=array();   
$messages[312] = 312;    
$messages[401] = 401;   
$messages[1599] = 1599;   
$messages[3] = 3;    

unset($messages[3]); // no search needed

#20


3  

As per your requirement "each value can only be there once" if you are just interested in keeping unique values in your array, then the array_unique() might be what you are looking for.

根据您的需求,“每个值只能在那里一次”,如果您只是想在数组中保留惟一的值,那么array_unique()可能就是您要找的对象。

Input:

输入:

$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);

Result:

结果:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

#21


2  

Or a one-liner using the or operator:

或使用或操作人员:

($key = array_search($del_val, $messages)) !== false or unset($messages[$key]);

#22


2  

The accepted answer, converts the array to associative array, so, if you would like to keep it as non associative array with the accepted answer, you may have to use array_values too.

被接受的答案,将数组转换为关联数组,因此,如果您想将它作为非关联数组保留为已接受的答案,那么您可能也必须使用array_values。

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

The reference is here

这里的引用

#23


1  

you can refer this URL : for function

您可以参考这个URL: for函数。

array-diff-key()

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_key($array1, $array2));
?>

Then output should be,

然后输出应该,

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

#24


1  

single liner code (thanks to array_diff() ), use following:

单行代码(感谢array_diff()),使用如下:

$messages = array_diff($messages, array(401));

#25


0  

Another idea to delete a value of an array, use array_diff. If I want to

另一个删除数组值的方法是使用array_diff。如果我想

$my_array = array(1=>"a", "second_value"=>"b", 3=>"c", "d");
$new_array_without_value_c = array_diff($my_array, array("c"));

(Doc : http://php.net/manual/fr/function.array-diff.php)

(文档:http://php.net/manual/fr/function.array-diff.php)

#1


1182  

Using array_search() and unset, try the following:

使用array_search()和unset,尝试以下方法:

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 false-y value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.

array_search()返回它找到的元素的键,可以使用unset()来从原始数组中移除该元素。如果失败,它将返回FALSE,但是它可以返回一个错误的成功值(例如,您的键可能是0),这就是为什么要使用严格的比较!

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

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

#2


429  

Well, deleting an element from array is basically just set difference with one element.

从数组中删除一个元素基本上就是用一个元素来设置不同。

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.

免责声明:请注意,我的解决方案生成一个数组的新副本,同时保持旧的数组不变,而不与被接受的答案相冲突。可能会稍微慢一点。

#3


91  

One interesting way is by using array_keys():

一个有趣的方法是使用array_keys():

foreach (array_keys($messages, 401, true) as $key) {
    unset($messages[$key]);
}

The array_keys() function takes two additional parameters to return only keys for a particular value and whether strict checking is required (i.e. using === for comparison).

array_keys()函数使用两个额外的参数,只返回特定值的键,以及是否需要严格检查(例如,使用===进行比较)。

This can also remove multiple array items with the same value (e.g. [1, 2, 3, 3, 4]).

这还可以删除具有相同值的多个数组项(例如,[1,2,3,3,4])。

#4


40  

If you know for definite that your array will contain only one element with that value, you can do

如果您确定您的数组只包含一个具有该值的元素,您可以这样做。

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

If, however, your value might occur more than once in your array, you could do this

但是,如果您的值在数组中不止一次发生,您可以这样做。

$array = array_filter($array, function($e) use ($del_val) {
    return ($e !== $del_val);
});

Note: The second option only works for PHP5.3+ with Closures

注意:第二个选项只适用于使用闭包的PHP5.3+。

#5


34  

$fields = array_flip($fields);
unset($fields['myvalue']);
$fields = array_flip($fields);

#6


21  

Have a look at following code:

看看下面的代码:

$arr = array('nice_item', 'remove_me', 'another_liked_item', 'remove_me_also');

You can do:

你能做什么:

$arr = array_diff($arr, array('remove_me', 'remove_me_also'));

And that will get you this array:

这样就得到了这个数组

array('nice_item', 'another_liked_item')

#7


15  

Or simply, manual way:

或简单,手动方式:

foreach ($array as $key => $value){
    if ($value == $target_value) {
        unset($array[$key]);
    }
}

This is the safest of them because you have full control on your array

这是最安全的,因为您可以完全控制您的数组。

#8


15  

The Best way is array_splice

最好的方法是array_splice。

array_splice($array, array_search(58, $array ), 1);

Reason for Best is here at http://www.programmerinterview.com/index.php/php-questions/how-to-delete-an-element-from-an-array-in-php/

最好的原因是这里的http://www.programmerinterview.com/index.php/php/howto -delete-an- arrayin -php/。

#9


14  

By the following code, the repetitive values will be removed from the $messages.

通过下面的代码,将从$messages中删除重复的值。

$messages = array_diff($messages, array(401));

(消息= array_diff美元消息,阵列(401));

#10


9  

function array_remove_by_value($array, $value)
{
    return array_values(array_diff($array, array($value)));
}

$array = array(312, 401, 1599, 3);

$newarray = array_remove_by_value($array, 401);

print_r($newarray);

Output

输出

Array ( [0] => 312 [1] => 1599 [2] => 3 )

数组([0]=> 312 [1]=> 1599 [2]=> 3)

#11


7  

To delete multiple values try this one

要删除多个值,请尝试这个。

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

#12


7  

you can do:

你能做什么:

unset($messages[array_flip($messages)['401']]);

Explanation: Delete the element that has the key 401 after flipping the array.

说明:删除在翻转数组后拥有键401的元素。

#13


6  

If you have > php5.3, there is the one line code :

如果你有> php5.3,有一行代码:

$array = array_filter($array, function($i) use ($value){return $i != $value;}); 

#14


5  

Borrowed the logic of underscoreJS _.reject and created two functions (people prefer functions!!)

借用了underscoreJS的逻辑。拒绝和创建两个函数(人们喜欢函数!!)

array_reject_value: This function is simply rejecting the value specified (also works for PHP4,5,7)

array_reject_value:这个函数简单地拒绝指定的值(也适用于PHP4、5、7)

function array_reject_value(array &$arrayToFilter, $deleteValue) {
    $filteredArray = array();

    foreach ($arrayToFilter as $key => $value) {
        if ($value !== $deleteValue) {
            $filteredArray[] = $value;
        }
    }

    return $filteredArray;
}

array_reject: This function is simply rejecting the callable method (works for PHP >=5.3)

array_reject:这个函数简单地拒绝callable方法(用于PHP >=5.3)

function array_reject(array &$arrayToFilter, callable $rejectCallback) {

    $filteredArray = array();

    foreach ($arrayToFilter as $key => $value) {
        if (!$rejectCallback($value, $key)) {
            $filteredArray[] = $value;
        }
    }

    return $filteredArray;
}

So in our current example we can use the above functions as follows:

在我们当前的例子中,我们可以使用上面的函数如下:

$messages = [312, 401, 1599, 3, 6];
$messages = array_reject_value($messages, 401);

or even better: (as this give us a better syntax to use like the array_filter one)

或者更好:(因为这给了我们更好的语法,可以像array_filter一样使用)

$messages = [312, 401, 1599, 3, 6];
$messages = array_reject($messages, function ($value) {
    return $value === 401;
});

The above can be used for more complicated stuff like let's say we would like to remove all the values that are greater or equal to 401 we could simply do this:

上面可以用来做更复杂的事情比如我们想要移除所有大于或等于401的值我们可以这样做:

$messages = [312, 401, 1599, 3, 6];
$greaterOrEqualThan = 401;
$messages = array_reject($messages, function ($value) use $greaterOrEqualThan {
    return $value >= $greaterOrEqualThan;
});

#15


4  

Get the key with array_search().

使用array_search()获取密钥。

#16


4  

@Bojangles answer did help me. Thank you.

@Bojangles的回答确实帮助了我。谢谢你!

In my case, the array could be associative or not, so I added this function

在我的例子中,数组可以是关联的,也可以不是,所以我添加了这个函数。

function test($value, $tab) {

 if(($key = array_search($value, $tab)) !== false) {
    unset($tab[$key]); return true;

 } else if (array_key_exists($value, $tab)){
        unset($tab[$value]); return true;

 } else {
    return false; // the $value is not in the array $tab
 }

}

Regards

问候

#17


3  

If your values you want to delete are, or can, be in an array. Use the array_diff function. Seems to work great for things like this.

如果您想要删除的值是(或可以)在数组中。array_diff函数使用。似乎对这样的事情很有用。

array_diff

array_diff

$arrayWithValuesRemoved = array_diff($arrayOfData, $arrayOfValuesToRemove);

#18


3  

OK.. I know this is not efficient at all but is simple, intuitive and easy to read.
So if someone is looking for a not so fancy solution which can be extended to work with more values, or more specific conditions .. here is a simple code:

好吧. .我知道这一点都不高效,但简单、直观、易于阅读。因此,如果有人在寻找一个不那么奇特的解决方案,可以扩展到更有价值的工作,或者更具体的条件。这里有一个简单的代码:

$result = array();
$del_value = 401;
//$del_values = array(... all the values you don`t wont);

foreach($arr as $key =>$value){
    if ($value !== $del_value){
        $result[$key] = $value;
    }

    //if(!in_array($value, $del_values)){
    //    $result[$key] = $value;
    //}

    //if($this->validete($value)){
    //      $result[$key] = $value;
    //}
}

return $result

#19


3  

If you don't know its key it means it doesn't matter.

如果你不知道它的关键,那就意味着它无关紧要。

You could place the value as the key, it means it will instant find the value. Better than using searching in all elements over and over again.

您可以将该值作为键,这意味着它将立即找到该值。比在所有元素中反复搜索要好。

$messages=array();   
$messages[312] = 312;    
$messages[401] = 401;   
$messages[1599] = 1599;   
$messages[3] = 3;    

unset($messages[3]); // no search needed

#20


3  

As per your requirement "each value can only be there once" if you are just interested in keeping unique values in your array, then the array_unique() might be what you are looking for.

根据您的需求,“每个值只能在那里一次”,如果您只是想在数组中保留惟一的值,那么array_unique()可能就是您要找的对象。

Input:

输入:

$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);

Result:

结果:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

#21


2  

Or a one-liner using the or operator:

或使用或操作人员:

($key = array_search($del_val, $messages)) !== false or unset($messages[$key]);

#22


2  

The accepted answer, converts the array to associative array, so, if you would like to keep it as non associative array with the accepted answer, you may have to use array_values too.

被接受的答案,将数组转换为关联数组,因此,如果您想将它作为非关联数组保留为已接受的答案,那么您可能也必须使用array_values。

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

The reference is here

这里的引用

#23


1  

you can refer this URL : for function

您可以参考这个URL: for函数。

array-diff-key()

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_key($array1, $array2));
?>

Then output should be,

然后输出应该,

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

#24


1  

single liner code (thanks to array_diff() ), use following:

单行代码(感谢array_diff()),使用如下:

$messages = array_diff($messages, array(401));

#25


0  

Another idea to delete a value of an array, use array_diff. If I want to

另一个删除数组值的方法是使用array_diff。如果我想

$my_array = array(1=>"a", "second_value"=>"b", 3=>"c", "d");
$new_array_without_value_c = array_diff($my_array, array("c"));

(Doc : http://php.net/manual/fr/function.array-diff.php)

(文档:http://php.net/manual/fr/function.array-diff.php)