How to remove a specific value from an array in PHP

In this tutorial, we will learn about how to remove a specific value or an element in an array related to a particular key in PHP script.

Hope this tutorial will be very helpful for you and you can make better use of given code snippets in your learning skill.

Remove specific elements from an Array in PHP

So, let’s get started,

In this tutorial, we will learn about three different functions one by one to remove a specific element from an array in PHP.

  1. using unset() function.
  2. using array_filter() function.

unset() function

The unset() function uses a particular key as an argument. This function deletes an element related to a particular key in an array. After the removal of a particular element from an array, the associated key and value don’t change.

<?php  

$array = array('C', 'O', 'D', 'E', 'S');
  
// Display the array element before unset()
print_r($array);
  
// Use unset() function to delete index 1 element 
unset($array[2]);//here we are passing key
  
// Display the array element after unset()
print_r($array);
  
?>

OUTPUT:

Array
(
    [0] => C
    [1] => O
    [2] => D
    [3] => E
    [4] => S
)
Array
(
    [0] => C
    [1] => O
    [3] => E
    [4] => S
)

array_filter() function

The array_filter() function is built-in PHP and it filters out the particular element from an array using a callback function. Here, arrays keys are preserved.

<?php
function remove($value)
{
  return $value != 'PHP';
}

$tutorial = array('key1' => 'Code', 'key2' => 'Speedy', 'key3' => 'PHP', 'key4' => 'Tutorial');
print_r($tutorial);

//after array_filter()
print_r(array_filter($tutorial,"remove"));
?>
OUTPUT:
Array
(
    [key1] => Code
    [key2] => Speedy
    [key3] => PHP
    [key4] => Tutorial
)
Array
(
    [key1] => Code
    [key2] => Speedy
    [key4] => Tutorial
)

Hope you enjoyed this tutorial, do share with your friends.

You can also visit:

Leave a Reply

Your email address will not be published.