Skip to content

Remove specific value from array using php?

Last updated on March 31, 2016

This post shows the possible ways to remove specific element from array based on value of the element.

Removing specific value Using array_diff()

Using this method we can remove one or more elements where using other methods we can only remove/delete one element at a given instance.

function remove_element($array,$value) {
  return array_diff($array, (is_array($value) ? $value : array($value)));
}

$myArray = array('php', 'laravel', '.net', 'java', 'c#', 'javascript');

$result = remove_element($myArray,'.net');

print_r($result);

// output : Array ( [0] => php [1] => laravel [3] => java [4] => c# [5] => javascript )

Removing specific value using array_search()

Using this method we can only remove one element at given instance. If there are two values with the same text it will remove first element only.

function remove_element(&$array,$value) {
 if(($key = array_search($value,$array)) !== false) {
       unset($array[$key]);
  }    
}

$myArray = array('php', 'laravel', '.net', 'java', 'c#', 'javascript');
remove_element($myArray,'php');
print_r($myArray);

Removing specific value using array_keys()

If there can be multiple items with the same value, you can use array_keys to get the keys to all items as shown below.

function remove_element($array,$value) {
 foreach (array_keys($array, $value) as $key) {
    unset($array[$key]);
 }  
  return $array;
}

$myArray = array('php', 'laravel', '.net', 'java', 'c#', 'javascript','php');
$result = remove_element($myArray,'php');
print_r($result);

// output : Array ( [1] => laravel [2] => .net [3] => java [4] => c# [5] => javascript ) 

That is it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments