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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -