Skip to content
Advertisement

How to handle nulls when doing a sum in php

I have the following data of which I’m trying to sum up the total fare but php keeps throwing this error Warning: A non-numeric value encountered in....

$read_one_vehicle_response = '
                            {
                                "response_code": 0,
                                "response_message": "Request processed successfully",
                                "id": "1",
                                "ticket": [
                                    {
                                        "id": "1",
                                        "total_fare": "1000",
                                        "status": "Paid"
                                    },
                                    {
                                        "id": "2",
                                        "total_fare": "80",
                                        "status": "Paid"
                                    },
                                    {
                                        "id": null,
                                        "total_fare": null,
                                        "status": null
                                    }
                                ],
                                "created": "2020-09-12 15:42:29",
                                "modified": "2020-09-12 20:42:29",
                                "status": "Active"
                            }';


$income = "";

foreach (json_decode($read_one_vehicle_response, true)["ticket"] as $ticket) {

    if (is_numeric($ticket{"total_fare"})) {
       $total_fare = $ticket{"total_fare"};
    }
    else {
        $total_fare = 0.00;
    }
    $income += $total_fare;
}

echo "Total: $income";

I have tried the above, it adds up the numbers correctly but still keeps throwing the error. What is the correct way of handling this error? I

Advertisement

Answer

You are adding up string values cast them to float

$income = floatval(0);

foreach (json_decode($read_one_vehicle_response, true)["ticket"] as $ticket) {

    if (is_numeric($ticket{"total_fare"})) {
       $total_fare = floatval($ticket{"total_fare"});
    }
    else {
        $total_fare = 0.00;
    }
    $income += $total_fare;
}

echo "Total: $income";
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement