Tim
Tim

Reputation: 395

Search and remove from multidimensional array

If I a value ID equals 1 and search an array I like to remove from the array itself where ID is 1 if found.

Array (
[0] => Array
    (
        [id] => 1
    )
[1] => Array
    (
        [id] => 4
    )
[2] => Array
    (
        [id] => 5
    )
[3] => Array
    (
        [id] => 7
    )
)

new array

Array (
[0] => Array
    (
        [id] => 4
    )
[1] => Array
    (
        [id] => 5
    )
[2] => Array
    (
        [id] => 7
    )
)

I am using search_array, and I am assuming that because it is multidimensional it isn't finding it. Is there a way to search an array like above?

Upvotes: 4

Views: 5769

Answers (3)

GSto
GSto

Reputation: 42350

If you just checking a single value, why not just use a foreach loop?

foreach ( $arr as $key => $value )
  {
    if ( $value['id'] == '1' )
      {
        unset( $arr[$key] );
      }
  }

Upvotes: 10

salathe
salathe

Reputation: 51950

Another approach would be like (assumes you're filtering out ids of integer 1):

$filtered = array_filter($arr, function ($val) { return $val['id'] !== 1; });

Note the above uses the cunningly named array_filter function with an anonymous function as the callback (which does the filtering; you could use a 'normal' named function if preferred, or if you're not embracing PHP 5.3 yet).

Upvotes: 5

Lekensteyn
Lekensteyn

Reputation: 66375

$arr = array(/* your array */);
$remove = 1;

foreach($arr as $key=>$val){
   if($val['id'] == $remove){
      unset($arr[$key]);
   }
}

Upvotes: 2

Related Questions