Handling null value when casting to float

arrays, encode, highcharts, json, php

Solution

You can do it by using a ternary operator. It will check for a condition then execute the second argument (what is between the `?` and the `:`), else it will execute the third argument (what is after the `:`).

$data[] = array((float)$datetime, is_null($temp_cellule) ? null : (float)$temp_cellule);

A ternary operator is a shorthand operator for an if-else then assign operator. As it returns the value of the second or third argument.

This would be the same thing as writing it like that :

if(is_null($temp_cellule)){
    $data[] = array((float)$datetime, null);
} else {
    $data[] = array((float)$datetime, (float)$temp_cellule);
}

Note that depending on how many times this case is present in your code you could make an utility function with it.

function handleFloat($value){
    return is_null($value) ? null : (float)$value;
}

Then you would just write :

$data[] = array((float)$datetime, handleFloat($temp_cellule));

This could help to keep your code DRY.

Problem

I'm on a project using Highcharts. A bit of php file: ``` $sql = "SELECT unix_timestamp(`datetime`) as `datetime`, `temp_cellule`, `temp_exterieur` FROM `tablebase`"; $result = mysql_query($sql); $data = array(); while ($row = mysql_fetch_array($result)) { extract($row); $datetime += 3600; //GMT+1 $datetime *= 1000; //UNIX_TIMESTAMP to java $data[] = array((float)$datetime,(float)$temp_cellule); $data2[]= array((float)$datetime,(float)$temp_exterieur); } $array[] = json_encode($data); $array2[] = json_encode($data2); ``` With this code: `$data2[]= array((float)$datetime,(float)$temp_cellule);` I get a good format but Highcharts does not recognize the value "null" because it's not a float so it's converted to 0 : ``` [[1362133360000,25],[1362136955000,0],[1362140579000,35] ``` But, if I use: `$data[] = array($datetime,$temp_cellule);` (without casting to float) I get the good format for "datetime" and "null" but not for temp_cellule because of " " : ``` [[1362133360000,"25"],[1362136955000,null],[1362140579000,"35"]] ``` And I want: ``` [[1362133360000,25],[1362136955000,null],[1362140579000,35]] ``` How can I achieve that?

Original source