-1

How do I remove NaN values from an array in php?

$array = [1, 3, 5, 3, float(NaN), 4, float(NaN)];
$desired_result = [1, 3, 5, 3, 4];

To remove any other element, I found this solution, but I can't get it to work for NaN. https://stackoverflow.com/a/7225113/9606753

Context: I am reading data from an rrd Database. I want to calculate the mean across several data entries, however at least one of them is float(NaN).

Max J.
  • 153
  • 12

1 Answers1

1

Use array_filter to remove NaN with is_nan function.

$array = [1, 3, 5, 3, float(NaN), 4, float(NaN)];
$filtered_array = array_filter($array, function ($element) {
    return !is_nan($element);
});

Note: This will also remove numbers that are stored as strings, '21' for example would be removed.

Josh Bonnick
  • 2,281
  • 1
  • 10
  • 21
  • How could I modify this to keep string numbers? – Max J. Jan 21 '22 at 19:53
  • 2
    [is_numeric](https://www.php.net/manual/en/function.is-numeric.php) might be better, especially since `float(NaN)` is not a valid PHP structure, and is most likely a string coming from the DB anyway – aynber Jan 21 '22 at 19:55
  • is_numeric returns true when passing NaN to it. `var_dump(is_numeric(sqrt(-1)));` – Josh Bonnick Jan 21 '22 at 19:57
  • 1
    For me, it keeps numbers stored as string. This is a perfect solution to me. Thank you! `````` – Max J. Jan 21 '22 at 20:01