Delete Array Elements By Value in PHP

In this tutorial we will see How To Delete Array Elements By Value in PHP. We can use array_search() and unset() functions or array_diff() function or array_keys() function for this purpose.

We have listed three simple methods to delete array elements by value in PHP.

Using array_search() function and unset()

We can simply use array_search() function and unset() to delete array elements by value.

array_search() function

The array_search() function searches an array for a value and it returns the key for that value.

unset() function

unset() destroys or deletes the specified variable.

In first method, array_search() function will look for a specified value and it will return it's key using which unset() function will delete the value.

Take a look at the code given below.

<?php
if (($key = array_search($value, $array)) !== false) {
    unset($array[$key]);
}
?>

Strict comparison !== is used in the code.

$value variable will be deleted from the array.

Using array_diff() function

We can also use simple array_diff() function to delete array element of an array.

array_diff() function

array_diff() function compares values of two arrays and it returns the difference.

This will also remove the specified value from the array if present.

See the example below.

<?php
$newArray =array_diff( [781, 301, 98, 1242], [1242] );
print_r($newArray);
?>

Note: This method is a bit slow and it creates the new array.

Using array_keys() function

array_keys() function can also be used to delete array element.

array_keys() function

array_keys() function returns an array containing the keys.

We have to define the 'value' whose key we need along side the second parameter which in this case is 'true'.

Take a look at the code given below.

<?php
foreach (array_keys($array, 1242, true) as $key) {
    unset($array[$key]);
}
?>

In above code the array_keys() function will look for the defined value inside the array and it will return it's key.

This key is then used to delete the value.

How To Append a String in PHP How To Prepend a String in PHP Replace a Word In String in PHP Convert Special Characters To HTML Entities PHP Find Number of Words in a String in PHP How To Find String Length in PHP How To Convert String To Uppercase in PHP How To Convert String To Lowercase in PHP How to Combine Two Strings in PHP Delete Array Elements By Value in PHP Get First Element Of Array In PHP Remove Numbers From String in PHP Convert Timestamp To Date in PHP Convert a Date to Timestamp in PHP Get Current Page Slug in PHP Check If Session Is Started in PHP Split Sentence Into Words in PHP Remove Last Character From String in PHP PHP Remove Spaces From String Replace Space With Dash in PHP Remove Everything from String Except Numbers Using PHP Get Full Url Address Using PHP Automatic Copyright Year Using PHP Generate 4 Digit Random Number in PHP How To Check If a Number is Prime using PHP Convert Integer to String in PHP