Open In App

How to perform Array Delete by Value Not Key in PHP ?

Last Updated : 10 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

An array is essentially a storage element for key-value pairs belonging to the same data type. If keys are specified explicitly, ids beginning from 0 as assigned to the values by the compiler on their own. Arrays allow a large variety of operations, like access, modification, and deletion upon the stored elements. The element positions are then adjusted accordingly. 

array_search() method

The value is first looked for in the array and then deleted successively. The array_search() method is used to search the array for a specified value. If it is successful, it returns the first corresponding key. The array_search() method is case-sensitive in terms of matching the specified value with the iterated values of the array. If there are multiple occurrences of the same value, only one is fetched out of it. 

Syntax:

array_search($value, $array);

Arguments:

  • $value: Value in the array that has to be searched.
  • $array: The array in which the value is searched.

Return value: Returns the key if the value exists in the array, else returns false. 

unset() method:

The unset() function in PHP is used to reset any variable. If unset() is called upon a user-defined function, it unsets the local variables. There can be many values that can be specified as arguments of this function. At least one variable is mandatory in the unset() method. 

Syntax:

unset($var);

Return value: The unset() function does not return any value.

PHP code:

<?php
#declaring an associative array
$arr = array(
    0 => 'GeeksForGeeks',
    1 => 'Python',
    2 => 'Java',
    3 => 'Physics'
);
#printing original array
echo ("Original Array: \n");
var_dump($arr);
#declaring the value to delete
$val = "Physics";
#finding the key on the basis of value
$key = array_search($val, $arr);
if (($key) !== false)
{
    #deleting the key found
    unset($arr[$key]);
}
echo ("<br><br>Modified Array: \n");
var_dump($arr);
?>

Output
Original Array: 
array(4) {
  [0]=>
  string(13) "GeeksForGeeks"
  [1]=>
  string(6) "Python"
  [2]=>
  string(4) "Java"
  [3]=>
  string(7) "Physics"
}
Modified Array: 
array(3) {
  [0]=>
  string(13) "GeeksForGeeks"
  [1]=>
  string(6) "Python"
  [2]=>
  string(4) "Java"
}

array_diff() method 

The array_diff() function in PHP is used to compare the values of two (or more) arrays and return the differences. It returns an array that contains the entries from array1 that are not contained in array2 or array3, etc. 

Syntax:

array_diff(arr, array1, array2, ...)

Arguments: 

  • arr: The array which is compared to the rest of the arrays from.
  • array1, array2….: The arrays to compare against the main array.

Return value: Returns an array containing the entries from arr that are not present in any of the other corresponding arrays.

We rely on the approach that we convert the value into an array using the array() method in PHP and then apply the array_diff() method over both of these arrays. The difference in comparison to the earlier method is that all the instances of the specified values are removed from the main array.

PHP code:

<?php
#declaring an associative array
$arr = array(
    0 => 'GeeksForGeeks',
    1 => 'Python',
    2 => 'Java',
    3 => 'Physics',
    4 => 'Python'
);
#printing original array
echo ("Original Array: \n");
var_dump($arr);
#declaring the value to delete
$val = array(
    "Python"
);
#finding the key on the basis of value
$arr = array_diff($arr, $val);

echo ("<br><br>Modified Array: \n");
var_dump($arr);
?>

Output
Original Array: 
array(5) {
  [0]=>
  string(13) "GeeksForGeeks"
  [1]=>
  string(6) "Python"
  [2]=>
  string(4) "Java"
  [3]=>
  string(7) "Physics"
  [4]=>
  string(6) "Python"
}
Modified Array: 
array(3) {
  [0]=>
  string(13) "GeeksForGeeks"
  [2]=>
  string(4) "Java"
  [3]=>
  string(7) "Physics"
}

PHP code: The following code illustrates the usage of this approach where the keys are not numerical IDs. 

<?php
#declaring an associative array
$arr = array(
    'key1' => 'GeeksForGeeks',
    'key2' => 'Python',
    'key3' => 'Java',
    'key4' => 'Physics',
    'key5' => 'Python'
);
#printing original array
echo ("Original Array: \n");
var_dump($arr);
#declaring the value to delete
$val = array(
    "Java"
);
#finding the key on the basis of value
$arr = array_diff($arr, $val);

echo ("<br><br>Modified Array: \n");
var_dump($arr);
?>

Output
Original Array: 
array(5) {
  ["key1"]=>
  string(13) "GeeksForGeeks"
  ["key2"]=>
  string(6) "Python"
  ["key3"]=>
  string(4) "Java"
  ["key4"]=>
  string(7) "Physics"
  ["key5"]=>
  string(6) "Python"
}
Modified Array: 
array(4) {
  ["key1"]=>
  string(13) "GeeksForGeeks"
  ["key2"]=>
  string(6) "Python"
  ["key4"]=>
  string(7) "Physics"
  ["key5"]=>
  string(6) "Python"
}

Using array_values() with array_splice()

To delete array elements by value using array_values() with array_splice() in PHP, find the key of the value, splice the array at that key, then reindex the array using array_values().

Example: In this example we declares an associative array, prints it, finds and removes a specified value (‘Java’), reindexes the array using array_values(), and then prints the modified array.

<?php
# Declaring an associative array
$arr = array(
    'key1' => 'GeeksForGeeks',
    'key2' => 'Python',
    'key3' => 'Java',
);

# Printing original array
echo "Original Array: \n";
var_dump($arr);

# Declaring the value to delete
$val = 'Java';

# Finding the key on the basis of value
$key = array_search($val, $arr);

# If the value exists in the array, delete it
if ($key !== false) {
    # Remove the element at the found key
    unset($arr[$key]);
    
    # Reindex the array
    $arr = array_values($arr);
}

echo "<br><br>Modified Array: \n";
var_dump($arr);
?>

Output
Original Array: 
array(3) {
  ["key1"]=>
  string(13) "GeeksForGeeks"
  ["key2"]=>
  string(6) "Python"
  ["key3"]=>
  string(4) "Java"
}
<br><br>Modified Array: 
array(2) {
  [0]=>
  string(13) "Geek...

Using a Loop

In the loop approach, you iterate through the array using foreach, checking each value. If the value matches the value to delete, unset() is used to remove the element from the array. This method is straightforward and allows conditional logic for value comparison.

Example:

<?php
$array = array('apple', 'banana', 'cherry', 'date');
$valueToDelete = 'banana';

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

// Reindex the array to maintain numerical indexing
$array = array_values($array);

print_r($array);
?>

Output
Array
(
    [0] => apple
    [1] => cherry
    [2] => date
)

Using array_filter()

This method involves defining a callback function that returns false for the value to be deleted, effectively removing it from the array.

Example: In this example, the deleteByValue function takes an array and the value to be deleted as parameters. It uses array_filter() with a callback function that checks each element. If the element matches the value to delete, the callback returns false, removing it from the array. The use ($valueToDelete) syntax allows the callback function to access the $valueToDelete variable from the outer scope.

<?php
    function deleteByValue($array, $valueToDelete) {
    return array_filter($array, function($value) use ($valueToDelete) {
        return $value !== $valueToDelete;
    });
}

// Example usage
$array = ['PHP', 'Java', 'Python', 'JavaScript', 'Java'];
$valueToDelete = 'Java';

$modifiedArray = deleteByValue($array, $valueToDelete);
print_r($modifiedArray);


?>

Output
Array
(
    [0] => PHP
    [2] => Python
    [3] => JavaScript
)

Using array_map() with array_keys()

Using array_map() with array_keys() in PHP involves creating a new array of keys where the specified value is found using array_keys(), then removing those elements with unset(). This method ensures that all instances of the value are efficiently deleted from the array.

Example

<?php

$array = ["apple", "banana", "cherry", "apple"];
$keys = array_keys($array, "banana");
foreach ($keys as $key) {
    unset($array[$key]);
}
print_r($array);

?>

Output
Array
(
    [0] => apple
    [2] => cherry
    [3] => apple
)


Next Article

Similar Reads

three90RightbarBannerImg