Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array delete by value (not key)

Tags:

arrays

php

I have a PHP array as follows:

$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. This might help: each value can only be there once.

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

like image 626
Adam Strudwick Avatar asked Aug 29 '11 00:08

Adam Strudwick


2 Answers

Using array_search() and unset, try the following:

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(). 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.

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

like image 57
Bojangles Avatar answered Oct 16 '22 10:10

Bojangles


Well, deleting an element from array is basically just set difference with one element.

array_diff( [312, 401, 15, 401, 3], [401] ) // removing 401 returns [312, 15, 3] 

It generalizes nicely, you can remove as many elements as you like at the same time, if you want.

Disclaimer: Note that my solution produces a new copy of the array while keeping the old one intact in contrast to the accepted answer which mutates. Pick the one you need.

like image 41
Rok Kralj Avatar answered Oct 16 '22 08:10

Rok Kralj