tags:

views:

36

answers:

4

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?

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

foreach($arr as $key=>$val){
   if($val['id'] == $remove){
      unset($arr[$key]);
   }
}
Lekensteyn
Thanks for your answer it works as well.
Tim
A: 

Assuming you meant array_search() and not search_array(), you're right, it doesn't search multidimensional arrays recursively.

I would just use a loop and access the array values manually:

$values = array(
    array('id' => 1), 
    array('id' => 4), 
    array('id' => 5), 
    array('id' => 7)
);

for ($i = 0, $c = count($values); $i < $c; $i++) {
    if ($values[$i]['id'] == 1) {
        unset($values[$i]);
    }
}
BoltClock
+1  A: 

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

for ($arr as $key => $value) {
 if($value['id'] == '1') {
   unset($arr[$key]);
 }
}
GSto
If I changed the for to a foreach, bingo that worked. I tried this myself and was not doing the if statement correctly; which lead me to posting a question here. Thanks for the answer!
Tim
+1  A: 

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).

salathe