Home > Backend Development > PHP Tutorial > 如何更优雅的删除数组元素

如何更优雅的删除数组元素

WBOY
Release: 2016-06-06 20:32:21
Original
1112 people have browsed it

<code>php</code><code>//类Python的remove
function remove($arr, $value)
{
    return array_values(array_diff($arr, array($value)));
}
var_dump(remove([1,2,3],3));//[1,2]
</code>
Copy after login
Copy after login

回复内容:

<code>php</code><code>//类Python的remove
function remove($arr, $value)
{
    return array_values(array_diff($arr, array($value)));
}
var_dump(remove([1,2,3],3));//[1,2]
</code>
Copy after login
Copy after login

那种语言呢,javascript还是php还是python。。。

<code>php</code><code>function remove($arr,$value)
{
    array_splice($arr,array_search($value,$arr),1);
    return $arr;
}
print_r(remove([1,2,3],3));
</code>
Copy after login

上面的答案只支持数字索引,参考下面方案:

<code>function remove($arr, $value)
{
    return array_diff($arr, array($value));
}
var_dump(remove([1,2,3],3));//[1,2]
var_dump(remove(['a'=>1,'b'=>2,'c'=>3],3));//['a'=>1,'b'=>2]
</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template