How to Remove Values from an Array in PHP

PHP array delete by value (not key)

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.

Deleting an element from an array in PHP

There are different ways to delete an array element, where some are more useful for some specific tasks than others.

Deleting a single array element

If you want to delete just one array element you can use unset() or alternatively \array_splice().

If you know the value and don’t know the key to delete the element you can use \array_search() to get the key. This only works if the element does not occur more than once, since \array_search returns the first hit only.

unset()

Note that when you use unset() the array keys won’t change. If you want to reindex the keys you can use \array_values() after unset(), which will convert all keys to numerically enumerated keys starting from 0.

Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
// ↑ Key which you want to delete

Output:

[
[0] => a
[2] => c
]

\array_splice() method

If you use \array_splice() the keys will automatically be reindexed, but the associative keys won’t change — as opposed to \array_values(), which will convert all keys to numerical keys.

\array_splice() needs the offset, not the key, as the second parameter.

Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
\array_splice($array, 1, 1);
// ↑ Offset which you want to delete

Output:

[
[0] => a
[1] => c
]

array_splice(), same as unset(), take the array by reference. You don’t assign the return values of those functions back to the array.

Deleting multiple array elements

If you want to delete multiple array elements and don’t want to call unset() or \array_splice() multiple times you can use the functions \array_diff() or \array_diff_key() depending on whether you know the values or the keys of the elements which you want to delete.

\array_diff() method

If you know the values of the array elements which you want to delete, then you can use \array_diff(). As before with unset() it won’t change the keys of the array.

Code:

$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = \array_diff($array, ["a", "c"]);
// └────────┘
// Array values which you want to delete

Output:

[
[1] => b
]

\array_diff_key() method

If you know the keys of the elements which you want to delete, then you want to use \array_diff_key(). You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.

Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_diff_key($array, [0 => "xy", "2" => "xy"]);
// ↑ ↑
// Array keys which you want to delete

Output:

[
[1] => b
]

If you want to use unset() or \array_splice() to delete multiple elements with the same value you can use \array_keys() to get all the keys for a specific value and then delete all elements.

\array_filter() method

If you want to delete all elements with a specific value in the array you can use \array_filter().

Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
$array = \array_filter($array, static function ($element) {
return $element !== "b";
// ↑
// Array value which you want to delete
});

Output:

[
[0] => a
[1] => c
]

PHP: How to remove specific element from an array?

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]);
}

Removing array item by value

It can be accomplished with a simple one-liner.

Having this array:

$arr = array('nice_item', 'remove_me', 'another_liked_item', 'remove_me_also');

You can do:

$arr = array_diff($arr, array('remove_me', 'remove_me_also'));

And the value of $arr will be:

array('nice_item', 'another_liked_item')

How to find a value in an array and remove it by using PHP array functions?

To search an element in an array, you can use array_search function and to remove an element from an array you can use unset function. Ex:

<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');

print_r($hackers);

// Search
$pos = array_search('Linus Trovalds', $hackers);

// array_seearch returns false if an element is not found
// so we need to do a strict check here to make sure
if ($pos !== false) {
echo 'Linus Trovalds found at: ' . $pos;

// Remove from array
unset($hackers[$pos]);
}

print_r($hackers);

You can refer: https://www.php.net/manual/en/ref.array.php for more array related functions.

Remove values from array based on another array

You can use array_diff,

array_diff($list_arr, $remove_arr);

Remove values with digit only from array - PHP

$data = array( 1 => "hello", 
2 => "foo",
3 => "192",
4 => "keep characters AND digits like a1e2r5",
);

$result = array_filter( $data,
function($arrayEntry) {
return !is_numeric($arrayEntry);
}
);

Or using slightly more modern PHP, with arrow functions:

$result = array_filter( $data, 
fn($arrayEntry) => !is_numeric($arrayEntry)
);

How to remove values from an array in PHP?

Use array_diff()

$new_array = array_diff($arrayB, $arrayA);

will return an array with all the elements from $arrayB that are not in $arrayA.

To do this with associative arrays use array_diff_assoc().

To remove a single value use:

unset($array[$key]);

You can of course loop that to do the equivalent of the array functions but there's no point in that.

How to remove values from an array if occurring more than one time?

You can use array functions and ditch the foreach loops if you wish:

Here is a one-liner:

Code:

$value = [10, 10, 5, 8];
var_export(array_keys(array_intersect(array_count_values($value),[1])));

As multi-line:

var_export(
array_keys(
array_intersect(
array_count_values($value),
[1]
)
)
);

Output:

array (
0 => 5,
1 => 8,
)

This gets the value counts as an array, then uses array_intersect() to only retain values that occur once, then turns the keys into the values of a zero-index array.

The above snippet works identically to @modsfabio's and @axiac's answers. The ONLY advantage in my snippet is brevity. It is possible that their solutions may outperform mine, but judging speed on relatively small data sets may be a waste of dev time. For anyone processing relatively large data sets, do your own benchmarking to find the technique that works best.


For lowest computational/time complexity, use a single loop and as you iterate conditionally populate a lookup array and unset() as needed.

Code: (Demo) (Crosslink to my CodeReview answer)

$values = [10, 10, 5, 8];

$found = [];
foreach ($values as $index => $value) {
if (!isset($found[$value])) {
$found[$value] = $index;
} else {
unset($values[$index], $values[$found[$value]]);
}
}
var_export($values);
// [2 => 5, 3 => 8]

A couple of notes:

  1. If processing float values, using a technique that stores the values as keys (as all of my snippets do), then the results may be incorrect because php will change floats to integers when used as keys.
  2. PHP is consistently much faster at searching for keys than it is at searching for values.

PHP remove specific item from array

With array_search you can get the first matching key of the given value, then you can delete it with unset.

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


Related Topics



Leave a reply



Submit