PHP: How to remove specific element from an array?

PhpArrays

Php Problem Overview


How do I remove an element from an array when I know the element's value? for example:

I have an array:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');

the user enters strawberry

strawberry is removed from $array.

To fully explain:

I have a database that stores a list of items separated by a comma. The code pulls in the list based on a user choice where that choice is located. So, if they choose strawberry they code pulls in every entry were strawberry is located then converts that to an array using split(). I want to them remove the user chosen items, for this example strawberry, from the array.

Php Solutions


Solution 1 - Php

Use array_search to get the key and remove it with unset if found:

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

array_search returns false (null until PHP 4.2.0) if no item has been found.

And if there can be multiple items with the same value, you can use array_keys to get the keys to all items:

foreach (array_keys($array, 'strawberry') as $key) {
    unset($array[$key]);
}

Solution 2 - Php

Use array_diff() for 1 line solution:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi', 'strawberry'); //throw in another 'strawberry' to demonstrate that it removes multiple instances of the string
$array_without_strawberries = array_diff($array, array('strawberry'));
print_r($array_without_strawberries);

...No need for extra functions or foreach loop.

Solution 3 - Php

if (in_array('strawberry', $array)) 
{
    unset($array[array_search('strawberry',$array)]);
}

Solution 4 - Php

If you are using a plain array here (which seems like the case), you should be using this code instead:

if (($key = array_search('strawberry', $array)) !== false) {
    array_splice($array, $key, 1);
}

unset($array[$key]) only removes the element but does not reorder the plain array.

Supposingly we have an array and use array_splice:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
array_splice($array, 2, 1);
json_encode($array); 
// yields the array ['apple', 'orange', 'blueberry', 'kiwi']

Compared to unset:

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[2]);
json_encode($array);
// yields an object {"0": "apple", "1": "orange", "3": "blueberry", "4": "kiwi"}

Notice how unset($array[$key]) does not reorder the array.

Solution 5 - Php

Just u can do single line .it will be remove element from array


$array=array_diff($array,['strawberry']);


Solution 6 - Php

You can use array filter to remove the items by a specific condition on $v:

$arr = array_filter($arr, function($v){
    return $v != 'some_value';
});

Solution 7 - Php

Will be like this:

 function rmv_val($var)
 {
     return(!($var == 'strawberry'));
 }
    
 $array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
   
 $array_res = array_filter($array, "rmv_val");

Solution 8 - Php

This is a simple reiteration that can delete multiple values in the array.

    // Your array
	$list = array("apple", "orange", "strawberry", "lemon", "banana");
	
	// Initilize what to delete
	$delete_val = array("orange", "lemon", "banana");
	
    // Search for the array key and unset	
	foreach($delete_val as $key){
		$keyToDelete = array_search($key, $list);
		unset($list[$keyToDelete]);
	}

Solution 9 - Php

I'm currently using this function:

function array_delete($del_val, $array) {
    if(is_array($del_val)) {
	     foreach ($del_val as $del_key => $del_value) {
		    foreach ($array as $key => $value){
			    if ($value == $del_value) {
    			    unset($array[$key]);
			    }
		    }
	    }
    } else {
	    foreach ($array as $key => $value){
    	    if ($value == $del_val) {
        	    unset($array[$key]);
    	    }
	    }
    }
    return array_values($array);
}

You can input an array or only a string with the element(s) which should be removed. Write it like this:

$detils = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$detils = array_delete(array('orange', 'apple'), $detils);

OR

$detils = array_delete('orange', $detils);

It'll also reindex it.

Solution 10 - Php

This question has several answers but I want to add something more because when I used unset or array_diff I had several problems to play with the indexes of the new array when the specific element was removed (because the initial index are saved)

I get back to the example :

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$array_without_strawberries = array_diff($array, array('strawberry'));

or

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[array_search('strawberry', $array)]);

If you print the result you will obtain :

foreach ($array_without_strawberries as $data) {
   print_r($data);
}

Result :

> apple
> orange
> blueberry
> kiwi

But the indexes will be saved and so you will access to your element like :

$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[3] > blueberry
$array_without_strawberries[4] > kiwi

And so the final array are not re-indexed. So you need to add after the unset or array_diff:

$array_without_strawberries = array_values($array);

After that your array will have a normal index :

$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[2] > blueberry
$array_without_strawberries[3] > kiwi

Related to this post : Re-Index Array

enter image description here

Hope it will help

Solution 11 - Php

A better approach would maybe be to keep your values as keys in an associative array, and then call array_keys() on it when you want to actual array. That way you don't need to use array_search to find your element.

Solution 12 - Php

The answer to https://stackoverflow.com/questions/7225070/php-array-delete-by-value-not-key Given by [https://stackoverflow.com/users/924109/rok-kralj][1]

IMO is the best answer as it removes and does not mutate

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. It might be a bit slower because of this.

[1]: https://stackoverflow.com/users/924109/rok-kralj "rok-kralj"

Solution 13 - Php

I was looking for the answer to the same question and came across this topic. I see two main ways: the combination of array_search & unset and the use of array_diff. At first glance, it seemed to me that the first method would be faster, since does not require the creation of an additional array (as when using array_diff). But I wrote a small benchmark and made sure that the second method is not only more concise, but also faster! Glad to share this with you. :)

https://glot.io/snippets/f6ow6biaol

Solution 14 - Php

Use this simple way hope it will helpful

foreach($array as $k => $value)
    {
      
        if($value == 'strawberry')
        {
          unset($array[$k]);
        }
    }

Solution 15 - Php

I would prefer to use array_key_exists to search for keys in arrays like:

Array([0]=>'A',[1]=>'B',['key'=>'value'])

to find the specified effectively, since array_search and in_array() don't work here. And do removing stuff with unset().

I think it will help someone.

Solution 16 - Php

Create numeric array with delete particular Array value

    <?php
    // create a "numeric" array
    $animals = array('monitor', 'cpu', 'mouse', 'ram', 'wifi', 'usb', 'pendrive');

    //Normarl display
    print_r($animals);
    echo "<br/><br/>";

    //If splice the array
    //array_splice($animals, 2, 2);
    unset($animals[3]); // you can unset the particular value
    print_r($animals);

    ?>

You Can Refer this link..

Solution 17 - Php

$remove= "strawberry";
$array = ["apple", "orange", "strawberry", "blueberry", "kiwi"];
foreach ($array as $key => $value) {
        if ($value!=$remove) {
        echo $value.'<br/>';
                continue;
        }
}

Solution 18 - Php

Using array_seach(), 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 "falsey" 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.

Solution 19 - Php

unset($array[array_search('strawberry', $array)]);

Solution 20 - Php

<?php 
$array = array("apple", "orange", "strawberry", "blueberry", "kiwi");
$delete = "strawberry";
$index = array_search($delete, $array);
array_splice($array, $index, 1);
var_dump($array);
?>

Solution 21 - Php

foreach ($get_dept as $key5 => $dept_value) {
                if ($request->role_id == 5 || $request->role_id == 6){
                    array_splice($get_dept, $key5, 1);
                }
            }

Solution 22 - Php

$detils = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
     function remove_embpty($values)
     {
        if($values=='orange')
        {
            $values='any name';
        }
        return $values;
     }
     $detils=array_map('remove_embpty',$detils);
    print_r($detils);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondcp3450View Question on Stackoverflow
Solution 1 - PhpGumboView Answer on Stackoverflow
Solution 2 - PhpillsView Answer on Stackoverflow
Solution 3 - PhpJohn CondeView Answer on Stackoverflow
Solution 4 - PhpericluwjView Answer on Stackoverflow
Solution 5 - Phpdılo sürücüView Answer on Stackoverflow
Solution 6 - PhpsrcspiderView Answer on Stackoverflow
Solution 7 - PhpD.MartinView Answer on Stackoverflow
Solution 8 - PhpmmrView Answer on Stackoverflow
Solution 9 - PhpjankalView Answer on Stackoverflow
Solution 10 - PhpJordan MontelView Answer on Stackoverflow
Solution 11 - PhpjishiView Answer on Stackoverflow
Solution 12 - PhphoundedView Answer on Stackoverflow
Solution 13 - PhpФлаттеристView Answer on Stackoverflow
Solution 14 - PhpSiraj AliView Answer on Stackoverflow
Solution 15 - PhpddsultanView Answer on Stackoverflow
Solution 16 - PhpSashtha ManikView Answer on Stackoverflow
Solution 17 - PhpKrishna JonnalagaddaView Answer on Stackoverflow
Solution 18 - PhpRavinder SinghView Answer on Stackoverflow
Solution 19 - Phpmax liView Answer on Stackoverflow
Solution 20 - PhpOnome Mine AdamuView Answer on Stackoverflow
Solution 21 - PhpRajendra RajputView Answer on Stackoverflow
Solution 22 - Phpuser3296940View Answer on Stackoverflow