1

I'm getting a Undefined offset error in a 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 are the two lines that I have this 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 I fix this? Appreciate your help

Qirel
  • 25,449
  • 7
  • 45
  • 62
Sherry
  • 35
  • 4
  • You get the error because if you pass `100` then the `$x_array` only contains `1` occurance i.e. `x_array[0]` You need to validate that the number entered is at least `1000` – RiggsFolly May 28 '16 at 19:13
  • Maybe you could use the simple [number_format()](http://php.net/manual/en/function.number-format.php) – RiggsFolly May 28 '16 at 19:16
  • Possible duplicate of [Reference - What does this error mean in PHP?](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – l'L'l May 28 '16 at 19:22
  • Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – andrewsi May 29 '16 at 00:33

2 Answers2

1

This happens, as RiggsFolly alluded to, when you are trying to access an array by key that does not exist. When your number_format does not return thousands and there is no comma sign, there will be only a single item in the array.

A simple fix would be to guard against by checking if the 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] : '';
Oli
  • 1,132
  • 1
  • 12
  • 26
0

As per documentation, number_format Formats a number with grouped thousands. So, if you pass number less than 1000, it will not grouped it and hence Undefined Offset Error as you will get only single item in $x_array. Possible solution could be

if(array_key_exists(1, $x_array)){
    $x_display = $x_array[0] . ((int) $x_array[1][0] !== 0 ? '.' . $x_array[1][0] : '');
}else{
    $x_display = $x_array[0];
}

if(array_key_exists($x_count_parts - 1, $x_parts)){
    $x_display .= $x_parts[$x_count_parts - 1];
}else{
    $x_display = "";
}
Vivek Pratap Singh
  • 9,326
  • 5
  • 21
  • 34