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

9
  • Just loop thorough and unset? Commented Mar 18, 2021 at 14:35
  • @Steven Without using a loop Commented Mar 18, 2021 at 14:36
  • Sorry, didn't read that. Why without a loop? Commented Mar 18, 2021 at 14:36
  • You can't do it without a loop. If you mean how to do it with built-in PHP functions, that's a different thing. But even those will internally loop. Commented Mar 18, 2021 at 14:37
  • @El_Vanja I can use array functions in php.I know it still use loops Commented Mar 18, 2021 at 14:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.