1

I have to import a txt file in my SQL database but the negative numbers are written with minus at the end (for ex : 11.719,88- or 13.791,47-).

When I import, negative numbers are positive. All my calcultate datas are false...

In my preprocess function (php), I tried many way to manage it but no success. Here is my function :

$char = $row['column_numbers'];
$char_array = str_split($char);
$last_char = end($char_array);
if($last_char == '-'){
    $char_array = preg_replace('/[-]/', '', $char_array);
    $char_array = '-'.$char_array;
    return $char_array;
}else{
    return $char_array;
}
$row["column_numbers"] = $char_array;

And I have also this message php : A PHP Error was encountered Severity: Notice Message: Array to string conversion

What am I do wrong? Thanks for help.

  • Not being a willing php participant, can you explain what this `$char_array = preg_replace('/[-]/', '', $char_array);` is doing ? Is it taking each individual array element, replacing with regex, then assigning to a temp array to be copied to and overwrite the original array ? –  Oct 08 '20 at 21:56
  • And can you concantenate a string to a character array ? `'-'.$char_array;` –  Oct 08 '20 at 21:58
  • 1
    This is simple string manipulation, and there's no need to get arrays or regular expressions involved. Try looking at `substr()`. – miken32 Oct 08 '20 at 22:00

1 Answers1

0

As hinted, string functions are sufficient here; specifically substr() and rtrim() come handy:

substr($col, -1) gives us the last character and rtrim($col, '-') helps to remove the last character.

function fixNegatives($col) {
    if(substr($col, -1) == '-') {
        return '-' . rtrim($col, '-');
    }else{
        return $col;
    }
}
wp78de
  • 18,207
  • 7
  • 43
  • 71