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

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

WBOY
WBOYOriginal
2016-06-06 20:32:211087browse

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

回复内容:

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

那种语言呢,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>

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

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