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

4

2 Answers 2

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] : '';
Sign up to request clarification or add additional context in comments.

Comments

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 = "";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.