Search code examples
phpsubstrstrlen

substr with strlen


I have an amount like 0003000, the last 2 digits are the decimal number. I want to transform 0003000 to 00030,00 (insert a decimal comma in front of the last 2 digits). I tried to do this with substring. I take the length of the string with strlen and then I make -2, but it ignores the -2.

Here is an example, why is it being ignored?

substr($this->arrCheck['amountsum'],0,(strlen($this->arrCheck['amountsum']-2)))

Solution

  • It's because your -2 is in the strlen function instead of outside it:

    strlen($this->arrCheck['amountsum']-2)
    

    Should be:

    strlen($this->arrCheck['amountsum'])-2
    

    But all in all you don't need to use strlen, since substr accepts a negative number as number of characters before the end of the string: PHP Manual

    So your whole code above can be replace by:

    substr($this->arrCheck['amountsum'], 0, -2)
    

    And the whole thing can be achieved by:

    substr($this->arrCheck['amountsum'], 0, -2).','.substr($this->arrCheck['amountsum'], -2)