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.
1 2 3 4 5 6 7 8 9 10 11 |
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.
1 2 3 4 5 6 7 8 9 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
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.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.