Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove element from array based on its value?

Tags:

php

i've got a regular array with keys and values.

is there a simple way to remove the array element based on its value or do i have to foreach-loop it through and check every value to remove it?

like image 526
ajsie Avatar asked Jan 30 '10 22:01

ajsie


People also ask

How do I remove a specific element from an array?

You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove.

How do I remove an element from a specific position?

How to remove an element at a specific position or index from an array in JavaScript? To remove elements or items from any position in an array, you can use the splice() array method in JavaScript. Consider this array of numbers, // number array const numArr = [23, 45, 67, 89];

How do you remove an element from an array using splice?

The splice() function changes the contents of an array by removing existing elements and/or adding new elements. In splice the second argument is the number of elements to remove. splice modifies the array in place and returns a new array containing the elements that have been removed.


2 Answers

array_diff:

$array = array('a','b','c');
$array_to_remove = array('a');

$final_array = array_diff($array,$array_to_remove);
// array('b','c');

edit: for more info: http://www.php.net/array_diff

like image 150
Mike Sherov Avatar answered Oct 04 '22 23:10

Mike Sherov


http://us3.php.net/array_filter

PHP 5.3 example to remove "foo" from array $a:

<?php
$a = array("foo", "bar");
$a = array_filter($a, function($v) { return $v != "foo"; });
?>

The second parameter can be any kind of PHP callback (e.g., name of function as a string). You could also use a function generating function if the search value is not constant.

like image 24
Matthew Avatar answered Oct 05 '22 01:10

Matthew