如何在数组中查找值并通过使用PHP数组函数将其删除?

问题描述 投票:52回答:10

如何查找数组中是否存在值,然后将其删除?删除后,我需要顺序索引顺序。

是否有任何PHP内置数组函数可以执行此操作?

php arrays function built-in
10个回答
91
投票

要搜索数组中的元素,可以使用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);

您可以参考:https://www.php.net/manual/en/ref.array.php了解更多与数组相关的功能。


-1
投票

要查找并删除数组中值的多个实例,我使用了下面的代码

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

93
投票
<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>

14
投票

您需要首先找到数组的键,这可以使用array_search()完成

完成后,请使用unset()

<?php
$array = array( 'apple', 'orange', 'pear' );

unset( $array[array_search( 'orange', $array )] );
?>

8
投票

[仅在要使用任何上述代码的情况下,请注意,当在“干草堆”中未找到“针头”时,array_search返回FALSE,因此这些示例将取消设置第一个(零索引)项目。改用它:

<?php
$haystack = Array('one', 'two', 'three');
if (($key = array_search('four', $haystack)) !== FALSE) {
  unset($haystack[$key]);
}
var_dump($haystack);

上面的示例将输出:

Array
(
    [0] => one
    [1] => two
    [2] => three
)

那很好!


4
投票

此解决方案是@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;
}

也可以在这里看看:PHP array delete by value (not key)


4
投票

未提及的一个功能是array_filter。您只需要传递一个回调函数,该回调函数将每个元素用作参数,如果该元素应保留或删除,则返回true或false。这也具有删除重复值的好处。

您可以这样使用它:

$myArray = array('one', 'two', 'deleteme', 'three');
$output = array_filter($myArray, function($val) { return $val != 'deleteme'; });

如果要重新索引数组,可以将结果传递给array_values,如下所示:

$output = array_values($output);

1
投票

首先,正如其他人提到的,您将使用“ 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.
?>

现在要重新索引同一数组,而不对任何数组值进行排序,您将需要使用“ array_values()”方法,如下所示:-

<?php
$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
?>

希望有帮助。


0
投票

这就是我的做法:

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

0
投票

好吧,这有点长,但是做了很多很酷的事情。

我试图过滤电子邮件列表,但排除某些域和电子邮件。

下面的脚本将...

  1. 删除具有特定域的任何记录
  2. 删除具有确切值的任何电子邮件。

首先,您需要一个包含电子邮件列表的数组,然后可以将某些域或单个电子邮件帐户添加到排除列表中。

然后它将在末尾输出干净记录的列表。

//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);
© www.soinside.com 2019 - 2024. All rights reserved.