从数组中删除符合 PHP 条件的某些元素?

Rai*_*iko 2 php arrays loops if-statement

所以我有一个数字数组:

$arr = [53, 182, 435, 591, 637];
Run Code Online (Sandbox Code Playgroud)

我想做的就是循环遍历每个元素,当某个条件为真时,它应该返回一个新数组,其中删除了符合条件的元素。

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]
  }
}
Run Code Online (Sandbox Code Playgroud)

med*_*ies 5

array_filter非常适合这种情况。

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

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

print_r($filtered_arr);  // [53, 435, 591]
Run Code Online (Sandbox Code Playgroud)

演示

请注意,短回调fn仅在 PHP7.4 或更高版本中可用