Senne Vandenputte Senne Vandenputte - 13 days ago 8
PHP Question

PHP function giving Undefined offset notice

I have a PHP function that returns the number of views on an article in thousands. For example, an article with 1240 views will be shown as 1.2k

The function I am using for this is working perfectly. This is the function:

function kconvert($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] : ''); <-- line 78
$x_display .= $x_parts[$x_count_parts - 1]; <!-- line 79
return $x_display;
};


The problem is that every time this function is executed, so on every page load, this writes a PHP notice to the error_log:

PHP Notice: Undefined offset: 1 in xxx/functions.php on line 78
PHP Notice: Undefined offset: -1 in xxx/functions.php on line 79


I highlighted the line numbers in the function above.

Is there any way to make sure this function is not giving a PHP notice every time it loads? Thanks!

Answer

Only test if the number is less than 1000, that is where the error occurs

function kconvert($num) {
  $x = round($num);
  if($num >= 1000){
  $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;
  echo $x_count_parts;
  $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;
  }else{
      return $num;
  }
};
Comments