Home > Back-end >  Remove certain elements from an array that fit a condition in PHP?
Remove certain elements from an array that fit a condition in PHP?

Time:03-26

So i have an a array of numbers:

$arr = [53, 182, 435, 591, 637];

All i am trying to do is loop trough each element and when a certain condition is true it should return a new array with the elements removed that have fitted the condition.

foreach($arr as $arry){
  echo "\n";
  echo $arry;
  
  if($arry % 13 == 0){
    //Remove 182 and 637 because they are divisible by 13,and make a new array: [53, 435, 591]
  }
}

CodePudding user response:

array_filter is ideal for this case.

$arr = [53, 182, 435, 591, 637];

$filtered_arr = array_filter($arr, fn($number) => $number % 13 !== 0);

print_r($filtered_arr);  // [53, 435, 591]

Demo

Note that the short callback fn is available starting for PHP7.4 or higher

CodePudding user response:

Does this answer your question?

$arr = [53, 182, 435, 591, 637];

for($i = 0; $i < count($arr); $i  ){
  if($arr[$i] % 13 == 0){
    unset($arr[$i]);
  }
}
$arr = array_values($arr); //reset indexes
  • Related