0

I have an array as follows

[0=>['classId'=>2,'Name'=>'John'],1=>['classId'=>3,'Name'=>'Doe'],2=>['classId'=>4,'Name'=>'Stayne']]

I need to remove the elements with classId 2 or 4 from array and the expected result should be

[0=>['classId'=>3,'Name'=>'Doe']]

How will i achieve this without using a loop.Hope someone can help

Vimal
  • 1,140
  • 1
  • 12
  • 26

2 Answers2

1

You can use array_filter in conjunction with in_array.

$array = [0=>['classId'=>2,'Name'=>'John'],1=>['classId'=>3,'Name'=>'Doe'],2=>['classId'=>4,'Name'=>'Stayne']];

var_dump(

    array_filter($array, function($item){return !in_array($item["classId"], [2,4]);})

);

Explanation

array_filter

Removes elements from the array if the call-back function returns false.

in_array

Searches an array for a value; returns boolean true/false if the value is (not)found.

Steven
  • 6,053
  • 2
  • 16
  • 28
0

Try this:

foreach array as $k => $v{
    if ($v['classId'] == 2){
        unset(array[$k]);
    }
}

I just saw your edit, you could use array_filter like so:

function class_filter($arr){
    return ($arr['classId'] == "whatever");
}
array_filter($arr, "class_filter");

Note: you'll still need to loop through a multi-dimensional array I believe.

bartholomew
  • 102
  • 8