Raitiko
Raitiko

Reputation: 187

Remove certain elements from an array that fit a condition in PHP?

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]
  }
}

Upvotes: 2

Views: 909

Answers (2)

medilies
medilies

Reputation: 2218

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 only available in PHP7.4 or higher

Upvotes: 5

outlaw
outlaw

Reputation: 307

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

Upvotes: 2

Related Questions