如何在数组中查找值并使用 PHP 数组函数将其删除?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3059392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find a value in an array and remove it by using PHP array functions?
提问by DEVOPS
How to find if a value exists in an array and then remove it? After removing I need the sequential index order.
如何查找数组中是否存在某个值然后将其删除?删除后我需要顺序索引顺序。
Are there any PHP built-in array functions for doing this?
是否有任何 PHP 内置数组函数可以执行此操作?
回答by mohitsoni
To search an element in an array, you can use array_searchfunction and to remove an element from an array you can use unsetfunction. Ex:
要搜索数组中的元素,可以使用array_search函数,而从数组中删除元素可以使用unset函数。前任:
<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');
print_r($hackers);
// Search
$pos = array_search('Linus Trovalds', $hackers);
echo 'Linus Trovalds found at: ' . $pos;
// Remove from array
unset($hackers[$pos]);
print_r($hackers);
You can refer: https://www.php.net/manual/en/ref.array.phpfor more array related functions.
更多数组相关函数可以参考:https: //www.php.net/manual/en/ref.array.php。
回答by Peter
<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>
回答by Kerry Jones
You need to find the key of the array first, this can be done using array_search()
您需要先找到数组的键,这可以使用array_search()来完成
Once done, use the unset()
完成后,使用unset()
<?php
$array = array( 'apple', 'orange', 'pear' );
unset( $array[array_search( 'orange', $array )] );
?>
回答by chyno
Just in case you want to use any of mentioned codes, be aware that array_searchreturns FALSE when the "needle" is not found in "haystack" and therefore these samples would unset the first (zero-indexed) item. Use this instead:
以防万一您想使用任何提到的代码,请注意,array_search当在“haystack”中找不到“needle”时返回 FALSE,因此这些样本将取消设置第一个(零索引)项目。改用这个:
<?php
$haystack = Array('one', 'two', 'three');
if (($key = array_search('four', $haystack)) !== FALSE) {
unset($haystack[$key]);
}
var_dump($haystack);
The above example will output:
上面的例子将输出:
Array
(
[0] => one
[1] => two
[2] => three
)
And that's good!
这很好!
回答by Kodos Johnson
You can use array_filterto filter out elements of an array based on a callback function. The callback function takes each element of the array as an argument and you simply return falseif that element should be removed. This also has the benefit of removing duplicate values since it scans the entire array.
您可以使用array_filter基于回调函数过滤掉数组元素。回调函数将数组的每个元素作为参数,false如果应该删除该元素,您只需返回即可。这也有删除重复值的好处,因为它扫描整个数组。
You can use it like this:
你可以这样使用它:
$myArray = array('apple', 'orange', 'banana', 'plum', 'banana');
$output = array_filter($myArray, function($value) { return $value !== 'banana'; });
// content of $output after previous line:
// $output = array('apple', 'orange', 'plum');
And if you want to re-index the array, you can pass the result to array_valueslike this:
如果你想重新索引数组,你可以array_values像这样传递结果:
$output = array_values($output);
回答by algorhythm
This solution is the combination of @Peter's solution for deleting multiple occurences and @chyno solution for removing first occurence. That's it what I'm using.
此解决方案是@Peter 删除多次出现的解决方案和@chyno 删除第一次出现的解决方案的组合。这就是我正在使用的。
/**
* @param array $haystack
* @param mixed $value
* @param bool $only_first
* @return array
*/
function array_remove_values(array $haystack, $needle = null, $only_first = false)
{
if (!is_bool($only_first)) { throw new Exception("The parameter 'only_first' must have type boolean."); }
if (empty($haystack)) { return $haystack; }
if ($only_first) { // remove the first found value
if (($pos = array_search($needle, $haystack)) !== false) {
unset($haystack[$pos]);
}
} else { // remove all occurences of 'needle'
$haystack = array_diff($haystack, array($needle));
}
return $haystack;
}
Also have a look here: PHP array delete by value (not key)
回答by Knowledge Craving
First of all, as others mentioned, you will be using the "array_search()" & the "unset()" methodsas shown below:-
首先,正如其他人提到的,您将使用“ array_search()”和“ unset()”方法,如下所示:-
<?php
$arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.
?>
Now to re-index the same array, without sorting any of the array values, you will need to use the "array_values()" method as shown below:-
现在要重新索引同一个数组,而不对任何数组值进行排序,您需要使用“ array_values()”方法,如下所示:-
<?php
$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
?>
Hope it helps.
希望能帮助到你。
回答by Mike Q
This is how I would do it:
这就是我将如何做到的:
$terms = array('BMW', 'Audi', 'Porsche', 'Honda');
// -- purge 'make' Porsche from terms --
if (!empty($terms)) {
$pos = '';
$pos = array_search('Porsche', $terms);
if ($pos !== false) unset($terms[$pos]);
}
回答by Craig Edmonds
Okay, this is a bit longer, but does a couple of cool things.
好的,这有点长,但做了一些很酷的事情。
I was trying to filter a list of emails but exclude certain domains and emails.
我试图过滤电子邮件列表但排除某些域和电子邮件。
Script below will...
下面的脚本将...
- Remove any records with a certain domain
- Remove any email with an exact value.
- 删除具有特定域的任何记录
- 删除任何具有确切值的电子邮件。
First you need an array with a list of emails and then you can add certain domains or individual email accounts to exclusion lists.
首先,您需要一个包含电子邮件列表的数组,然后您可以将某些域或单个电子邮件帐户添加到排除列表中。
Then it will output a list of clean records at the end.
然后它会在最后输出一个干净的记录列表。
//list of domains to exclude
$excluded_domains = array(
"domain1.com",
);
//list of emails to exclude
$excluded_emails = array(
"[email protected]",
"[email protected]",
);
function get_domain($email) {
$domain = explode("@", $email);
$domain = $domain[1];
return $domain;
}
//loop through list of emails
foreach($emails as $email) {
//set false flag
$exclude = false;
//extract the domain from the email
$domain = get_domain($email);
//check if the domain is in the exclude domains list
if(in_array($domain, $excluded_domains)){
$exclude = true;
}
//check if the domain is in the exclude emails list
if(in_array($email, $excluded_emails)){
$exclude = true;
}
//if its not excluded add it to the final array
if($exclude == false) {
$clean_email_list[] = $email;
}
$count = $count + 1;
}
print_r($clean_email_list);
回答by Brijesh Mishra
To find and remove multiple instance of value in an array, i have used the below code
要查找和删除数组中的多个值实例,我使用了以下代码
$list = array(1,3,4,1,3,1,5,8);
$new_arr=array();
foreach($list as $value){
if($value=='1')
{
continue;
}
else
{
$new_arr[]=$value;
}
}
print_r($new_arr);

