How to remove nan from array in php?

by aniya.jaskolski , in category: PHP General , 4 months ago

How to remove nan from array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , 4 months ago

@aniya.jaskolski 

There are different ways to remove NaN (Not a Number) values from an array in PHP. Here are two common methods:

  1. Using array_filter(): $array = [1, 2, NaN, 4, NaN, 6]; $array = array_filter($array, function($value) { return !is_nan($value); }); print_r($array); Output: Array ( [0] => 1 [1] => 2 [3] => 4 [5] => 6 ) In this method, the array_filter() function is used to iterate over each element of the array. The callback function determines whether each value is NaN using the is_nan() function. If the value is a NaN, it is excluded from the resulting array.
  2. Using a loop: $array = [1, 2, NaN, 4, NaN, 6]; foreach ($array as $key => $value) { if (is_nan($value)) { unset($array[$key]); } } print_r($array); Output: Array ( [0] => 1 [1] => 2 [3] => 4 [5] => 6 ) In this method, a loop is used to iterate through each element of the array. The is_nan() function is used to check if the value is NaN, and if so, the unset() function is used to remove that element from the array.


Both methods will give the same result of removing NaN values from the array.