Adam Strudwick
Adam Strudwick

Reputation: 13149

PHP array delete by value (not key)

I have a PHP array like so:

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

Given that the values in the array are unique, how can I delete the element with a given value (without knowing its key)?

Upvotes: 1185

Views: 1326378

Answers (21)

Abdul Jabbar
Abdul Jabbar

Reputation: 5951

The following answer using array_splice fails at 2 scenarios

  1. If the searched value is not found, it removes the first element
  2. It won't work with associative arrays.

Thus, it is not a good way to do. Not deleting my original answer because many others have also mentioned this array_splice as the best way. Therefore, updated my previous answer with reasons for it being the bad way to do.

Better if only removing 1 value from simple array

array_filter($array, fn($e) => $e !== $value)

Previous Original Answer Below

The Best way is array_splice

array_splice($array, array_search(58, $array ), 1);

Reason for Best is here at http://www.programmerinterview.com/index.php/php-questions/how-to-delete-an-element-from-an-array-in-php/

Upvotes: 38

Alexxus
Alexxus

Reputation: 992

Using array_filter and anonymous function:

$messages = array_filter($messages, function ($value) use ($del_val) {
    return $value != $del_val;
});

You can run a code example here: https://onlinephp.io/c/4f320

Upvotes: 3

SaidbakR
SaidbakR

Reputation: 13544

The accepted answer converts the array to associative array, so, if you would like to keep it as a non-associative array with the accepted answer, you may have to use array_values too.

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

The reference is linked here

Upvotes: 12

Koushik Das
Koushik Das

Reputation: 10813

PHP 7.4 or above

function delArrValues(array $arr, array $remove) {
    return array_filter($arr, fn($e) => !in_array($e, $remove));
};

So, if you have the array as

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

and you want to remove both 3, 312 from the $messages array, You'd do this

delArrValues($messages, [3, 312])

It would return

[401, 1599]

The best part is that you can filter multiple values easily, even there are multiple occurrences of the same value.

Upvotes: 14

fico7489
fico7489

Reputation: 8560

here is one simple but understandable solution:

$messagesFiltered = [];
foreach ($messages as $message) {
    if (401 != $message) {
        $messagesFiltered[] = $message;
    }
}
$messages = $messagesFiltered;

Upvotes: 0

Roy
Roy

Reputation: 4464

With PHP 7.4 using arrow functions:

$messages = array_filter($messages, fn ($m) => $m != $del_val);

To keep it a non-associative array wrap it with array_values():

$messages = array_values(array_filter($messages, fn ($m) => $m != $del_val));

Upvotes: 40

algo
algo

Reputation: 118

I think the simplest way would be to use a function with a foreach loop:

//This functions deletes the elements of an array $original that are equivalent to the value $del_val
//The function works by reference, which means that the actual array used as parameter will be modified.

function delete_value(&$original, $del_val)
{
    //make a copy of the original, to avoid problems of modifying an array that is being currently iterated through
    $copy = $original;
    foreach ($original as $key => $value)
    {
        //for each value evaluate if it is equivalent to the one to be deleted, and if it is capture its key name.
        if($del_val === $value) $del_key[] = $key;
    };
    //If there was a value found, delete all its instances
    if($del_key !== null)
    {
        foreach ($del_key as $dk_i)
        {
            unset($original[$dk_i]);
        };
        //optional reordering of the keys. WARNING: only use it with arrays with numeric indexes!
        /*
        $copy = $original;
        $original = array();
        foreach ($copy as $value) {
            $original[] = $value;
        };
        */
        //the value was found and deleted
        return true;
    };
    //The value was not found, nothing was deleted
    return false;
};

$original = array(0,1,2,3,4,5,6,7,4);
$del_val = 4;
var_dump($original);
delete_value($original, $del_val);
var_dump($original);

Output will be:

array(9) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
  [5]=>
  int(5)
  [6]=>
  int(6)
  [7]=>
  int(7)
  [8]=>
  int(4)
}
array(7) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [5]=>
  int(5)
  [6]=>
  int(6)
  [7]=>
  int(7)
}

Upvotes: 0

Rajendra Khabiya
Rajendra Khabiya

Reputation: 2030

To delete multiple values try this one:

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

Upvotes: 8

Qurashi
Qurashi

Reputation: 1467

you can do:

unset($messages[array_flip($messages)['401']]);

Explanation: Delete the element that has the key 401 after flipping the array.

Upvotes: 15

John Skoubourdis
John Skoubourdis

Reputation: 3289

Borrowed the logic of underscore.JS _.reject and created two functions (people prefer functions!!)

array_reject_value: This function is simply rejecting the value specified (also works for PHP4,5,7)

function array_reject_value(array &$arrayToFilter, $deleteValue) {
    $filteredArray = array();

    foreach ($arrayToFilter as $key => $value) {
        if ($value !== $deleteValue) {
            $filteredArray[] = $value;
        }
    }

    return $filteredArray;
}

array_reject: This function is simply rejecting the callable method (works for PHP >=5.3)

function array_reject(array &$arrayToFilter, callable $rejectCallback) {

    $filteredArray = array();

    foreach ($arrayToFilter as $key => $value) {
        if (!$rejectCallback($value, $key)) {
            $filteredArray[] = $value;
        }
    }

    return $filteredArray;
}

So in our current example we can use the above functions as follows:

$messages = [312, 401, 1599, 3, 6];
$messages = array_reject_value($messages, 401);

or even better: (as this give us a better syntax to use like the array_filter one)

$messages = [312, 401, 1599, 3, 6];
$messages = array_reject($messages, function ($value) {
    return $value === 401;
});

The above can be used for more complicated stuff like let's say we would like to remove all the values that are greater or equal to 401 we could simply do this:

$messages = [312, 401, 1599, 3, 6];
$greaterOrEqualThan = 401;
$messages = array_reject($messages, function ($value) use $greaterOrEqualThan {
    return $value >= $greaterOrEqualThan;
});

Upvotes: 6

Eric
Eric

Reputation: 97661

A one-liner using the or operator:

($key = array_search($del_val, $messages)) !== false or unset($messages[$key]);

Upvotes: 4

Ismael
Ismael

Reputation: 2340

If you don't know its key it means it doesn't matter.

You could place the value as the key, it means it will instantly find the value. Better than using searching in all elements over and over again.

$messages=array();   
$messages[312] = 312;    
$messages[401] = 401;   
$messages[1599] = 1599;   
$messages[3] = 3;    

unset($messages[3]); // no search needed

Upvotes: 7

d.raev
d.raev

Reputation: 9556

I know this is not efficient at all but is simple, intuitive and easy to read.
So if someone is looking for a not so fancy solution which can be extended to work with more values, or more specific conditions .. here is a simple code:

$result = array();
$del_value = 401;
//$del_values = array(... all the values you don`t wont);

foreach($arr as $key =>$value){
    if ($value !== $del_value){
        $result[$key] = $value;
    }

    //if(!in_array($value, $del_values)){
    //    $result[$key] = $value;
    //}

    //if($this->validete($value)){
    //      $result[$key] = $value;
    //}
}

return $result

Upvotes: 4

Mohd Abdul Mujib
Mohd Abdul Mujib

Reputation: 13948

As per your requirement "each value can only be there for once" if you are just interested in keeping unique values in your array, then the array_unique() might be what you are looking for.

Input:

$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);

Result:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

Upvotes: 1

Rok Kralj
Rok Kralj

Reputation: 48775

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.

Upvotes: 961

Bojangles
Bojangles

Reputation: 101533

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.

Upvotes: 2029

Victor Priceputu
Victor Priceputu

Reputation: 666

Or simply, manual way:

foreach ($array as $key => $value){
    if ($value == $target_value) {
        unset($array[$key]);
    }
}

This is the safest of them because you have full control on your array

Upvotes: 34

adlawson
adlawson

Reputation: 6431

If you know for definite that your array will contain only one element with that value, you can do

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

If, however, your value might occur more than once in your array, you could do this

$array = array_filter($array, function($e) use ($del_val) {
    return ($e !== $del_val);
});

Note: The second option only works for PHP5.3+ with Closures

Upvotes: 79

Ja͢ck
Ja͢ck

Reputation: 173652

One interesting way is by using array_keys():

foreach (array_keys($messages, 401, true) as $key) {
    unset($messages[$key]);
}

The array_keys() function takes two additional parameters to return only keys for a particular value and whether strict checking is required (i.e. using === for comparison).

This can also remove multiple array items with the same value (e.g. [1, 2, 3, 3, 4]).

Upvotes: 182

Rmannn
Rmannn

Reputation: 1353

$fields = array_flip($fields);
unset($fields['myvalue']);
$fields = array_flip($fields);

Upvotes: 48

tttony
tttony

Reputation: 5092

function array_remove_by_value($array, $value)
{
    return array_values(array_diff($array, array($value)));
}

$array = array(312, 401, 1599, 3);

$newarray = array_remove_by_value($array, 401);

print_r($newarray);

Output

Array ( [0] => 312 [1] => 1599 [2] => 3 )

Upvotes: 20

Related Questions