Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

php - PHP数组按值删除(不是键)(PHP array delete by value (not key))

I have a PHP array as follows:

(我有一个PHP数组,如下所示:)

$messages = [312, 401, 1599, 3, ...];

I want to delete the element containing the value $del_val (for example, $del_val=401 ), but I don't know its key.

(我想删除包含值$del_val的元素(例如$del_val=401 ),但是我不知道它的键。)

This might help: each value can only be there once .

(这可能会有所帮助: 每个值只能存在一次 。)

I'm looking for the simplest function to perform this task, please.

(我正在寻找执行此任务的最简单功能。)

  ask by Adam Strudwick translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using array_search() and unset , try the following:

(使用array_search()unset ,尝试以下操作:)

if (($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
}

array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset() .

(array_search()返回找到的元素的键,可以使用unset()从原始数组中删除该元素。)

It will return FALSE on failure, however it can return a false-y value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.

(如果失败,它将返回FALSE ,但是如果成功,它将返回false -y值(例如,您的键可能为0 ),这就是为什么要使用严格比较!==运算符的原因。)

The if() statement will check whether array_search() returned a value, and will only perform an action if it did.

(if()语句将检查array_search()是否返回值,并且只会执行一个动作。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...