如何使用 PHP 数组函数查找数组中的值并删除它?

发布于 2024-09-06 03:47:15 字数 71 浏览 3 评论 0 原文

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

有 PHP 内置数组函数可以做到这一点吗?

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?

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

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

发布评论

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

评论(11

南渊 2024-09-13 03:47:15
<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>
<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>
一束光,穿透我孤独的魂 2024-09-13 03:47:15

要搜索数组中的元素,可以使用array_search函数,要从数组中删除元素,可以使用unset函数。例如:

<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');

print_r($hackers);

// Search
$pos = array_search('Linus Trovalds', $hackers);

// array_seearch returns false if an element is not found
// so we need to do a strict check here to make sure
if ($pos !== false) {
    echo 'Linus Trovalds found at: ' . $pos;

    // Remove from array
    unset($hackers[$pos]);
}

print_r($hackers);

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

To search an element in an array, you can use array_search function and to remove an element from an array you can use unset function. Ex:

<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');

print_r($hackers);

// Search
$pos = array_search('Linus Trovalds', $hackers);

// array_seearch returns false if an element is not found
// so we need to do a strict check here to make sure
if ($pos !== false) {
    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.php for more array related functions.

够钟 2024-09-13 03:47:15

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

完成后,使用 unset()

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

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

You need to find the key of the array first, this can be done using array_search()

Once done, use the unset()

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

unset( $array[array_search( 'orange', $array )] );
?>
一向肩并 2024-09-13 03:47:15

以防万一您想使用任何提到的代码,请注意,当在“haystack”中找不到“needle”时,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
)

And that's good!

Just in case you want to use any of mentioned codes, be aware that array_search returns FALSE when the "needle" is not found in "haystack" and therefore these samples would unset the first (zero-indexed) item. Use this instead:

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

云之铃。 2024-09-13 03:47:15

您可以使用 array_filter 来根据回调函数过滤掉数组的元素。回调函数将数组的每个元素作为参数,如果应该删除该元素,您只需返回 false 即可。由于它会扫描整个数组,因此还具有删除重复值的优点。

你可以这样使用它:

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

如果你想重新索引数组,你可以将结果传递给 array_values 像这样:

$output = array_values($output);

You can use array_filter to 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 false if that element should be removed. This also has the benefit of removing duplicate values since it scans the entire array.

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_values like this:

$output = array_values($output);
不爱素颜 2024-09-13 03:47:15

该解决方案是@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 数组按值(而非键)删除

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.

/**
 * @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)

樱娆 2024-09-13 03:47:15

unset array_search 有一些非常可怕的副作用,因为它可能会意外地从数组中删除第一个元素,无论值如何:

        // bad side effects
        $a = [0,1,2,3,4,5];
        unset($a[array_search(3, $a)]);
        unset($a[array_search(6, $a)]);
        $this->log_json($a);
        // result: [1,2,4,5]
        // what? where is 0?
        // it was removed because false is interpreted as 0

        // goodness
        $b = [0,1,2,3,4,5];
        $b = array_diff($b, [3,6]);
        $this->log_json($b);
        // result: [0,1,2,4,5]

如果您知道该值保证在数组,就用它吧,但我认为 array_diff 更安全。 (我使用的是php7)

The unset array_search has some pretty terrible side effects because it can accidentally strip the first element off your array regardless of the value:

        // bad side effects
        $a = [0,1,2,3,4,5];
        unset($a[array_search(3, $a)]);
        unset($a[array_search(6, $a)]);
        $this->log_json($a);
        // result: [1,2,4,5]
        // what? where is 0?
        // it was removed because false is interpreted as 0

        // goodness
        $b = [0,1,2,3,4,5];
        $b = array_diff($b, [3,6]);
        $this->log_json($b);
        // result: [0,1,2,4,5]

If you know that the value is guaranteed to be in the array, go for it, but I think the array_diff is far safer. (I'm using php7)

誰ツ都不明白 2024-09-13 03:47:15
$data_arr = array('hello', 'developer', 'laravel' );


// We Have to remove Value "hello" from the array
// Check if the value is exists in the array

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



# output:
// It will Return unsorted Indexed array
print( $data_arr )


// To Sort Array index use this
$data_arr = array_values( $data_arr );


// Now the array key is sorted
$data_arr = array('hello', 'developer', 'laravel' );


// We Have to remove Value "hello" from the array
// Check if the value is exists in the array

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



# output:
// It will Return unsorted Indexed array
print( $data_arr )


// To Sort Array index use this
$data_arr = array_values( $data_arr );


// Now the array key is sorted
七度光 2024-09-13 03:47:15

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

希望有帮助。

First of all, as others mentioned, you will be using the "array_search()" & the "unset()" methodsas shown below:-

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

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

Hope it helps.

时光暖心i 2024-09-13 03:47:15

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

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

下面的脚本将...

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

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

  1. Remove any records with a certain domain
  2. 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);
叹倦 2024-09-13 03:47:15

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

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

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