Undefined offset PHP error 1 -
i'm getting undefined offset error in php function
error codes
php notice: undefined offset: 1
php notice: undefined offset: -1
function thousandscurrencyformat($num) { $x = round($num); $x_number_format = number_format($x); $x_array = explode(',', $x_number_format); $x_parts = array('k', 'm', 'b', 't'); $x_count_parts = count($x_array) - 1; $x_display = $x; $x_display = $x_array[0] . ((int) $x_array[1][0] !== 0 ? '.' . $x_array[1][0] : ''); $x_display .= $x_parts[$x_count_parts - 1]; return $x_display; }
these 2 lines have error
$x_display = $x_array[0] . ((int) $x_array[1][0] !== 0 ? '.' . $x_array[1][0] : ''); $x_display .= $x_parts[$x_count_parts - 1];
how can fix this? appreciate help
this happens, riggsfolly alluded to, when trying access array key not exist. when number_format not return thousands , there no comma sign, there single item in array.
a simple fix guard against checking if key exists:
$x_display = array_key_exists(1, $x_array) ? $x_array[0] . ((int) $x_array[1][0] !== 0 ? '.' . $x_array[1][0] : '') : $x_array[0] ; $x_display .= array_key_exists($x_count_parts - 1, $x_parts) ? $x_parts[$x_count_parts - 1] : '';
Comments
Post a Comment