Heim  >  Artikel  >  Backend-Entwicklung  >  如何更优雅的删除数组元素

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

WBOY
WBOYOriginal
2016-06-06 20:32:211049Durchsuche

<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>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:各位看看代码哪里错误了Nächster Artikel:php如何接入paypal支付