简体   繁体   中英

Removing an element from an array (PHP)

I want to remove an element from a PHP array (and shrink the array size). Just looking at the PHP docs, it seems this can be done using array_slice() and array_merge()

so I am guessing (off the top of my head) that some combination of array_merge() and array_slice will work. However, array_slice() requires an index (not a key), so I'm not sure how to quickly cobble these functions together for a solution.

Has anyone implemented such a function before?. I'm sure it must be only a few lines long, but I cant somehow get my head around it (its been one of those days) ...

Actually, I just came up with this cheesy hack when writing up this question....

function remove_from_array(array $in, value) {
   return array_diff($in, (array)$value);
}

too ugly? or will it work (without any shocking side effects)?

This functionality already exists; take a look at unset .

http://php.net/manual/en/function.unset.php


$a = array('foo' => 'bar', 'bar' => 'gork');
unset($a['bar']);
print_r($a);

output will be:

array(
[foo] => bar
)

array_filter函数,它使用回调函数从数组中仅选择所需的值。

you want an unset by value. loop through the array and unset the key by value.

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

/*
and if you want to create a new array with the keys reordered accordingly...
*/
$new_array = array_values($array);
unset($my_array['element']);

不行吗

此代码可以由单个array_filter($ arr)调用代替

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM