phparraysnanrrdtoolrrd

How to remove NaN from array in PHP?


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).


Solution

  • 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.