1

A php code is shown here

foreach ($icx_json_date as $key_date => $icx_value_date) {

        echo $icx_value_date["isd_out_traffic"] . ", ";
    }

the output for this code is

, , , , , , 14449.25, 881.50,

I want to replace the null output with zero and show the output as

0, 0, 0, 0, 0, 0, 14449.25, 881.50,

what changes should be done to do so?

4 Answers4

2

Use the short-hand conditional operator:

foreach ($icx_json_date as $key_date => $icx_value_date) {
    echo ($icx_value_date["isd_out_traffic"] ?: 0) . ", ";
}

x ?: y is x if x is not null, otherwise it's y.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • @Barmar That isn't the null coalescing operator (`??`)—you used the shorthand ternary operator, `?:`. In this case the output is the same, but in a case where a value could be undefined, the latter will emit an `E_NOTICE` which is often undesirable (but it does work back to PHP 5.3, whereas the null coalescing operator was introduced in PHP 7). Not trying to nit-pick, just know folks may be confused as to the diffrence (covered here: https://stackoverflow.com/questions/34571330/php-ternary-operator-vs-null-coalescing-operator as well) – justbeez Jul 14 '19 at 05:19
0

If all data should be numbers :

foreach ($icx_json_date as $key_date => $icx_value_date) {
    echo floatval($icx_value_date["isd_out_traffic"]) . ", ";
}
Chester
  • 722
  • 4
  • 6
0

You can use Null coalescing operator, If you are using PHP 7+

foreach ($icx_json_date as $key_date => $icx_value_date) {
    echo $icx_value_date["isd_out_traffic"]  ?? 0;
    echo  ", ";
}
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
0

You can totally omit the unnecessary $key_date => if you're not using it.
You'll have a tailing , which is generally undesirable.
Also you'll get warnings if the array key doesn't exist if it's going to be NULL (no reason to fill up logs depending on php settings).

I'm a fan of the "silence" operator instead of using isset in combination with the ternary/conditional operator. You can then simply typecast to float like so:

$out = [];
foreach ($icx_json_date as $icx_value_date) {
    $out[] = (float)@$icx_value_date['isd_out_traffic'];
}
echo implode(', ', $out);

If you don't want to pollute the current scope with any variables whatsoever, you can get fancier with something like this:

echo implode(', ',
    array_map(
        function($ar){ return (float)@$ar['isd_out_traffic']; },
        $icx_json_date
    )
);

Probably faster to use the ?: operator though.

Ultimater
  • 4,647
  • 2
  • 29
  • 43