Home > OS >  meaning of this statement (int)str_replace(',', '',str_replace('.', &#
meaning of this statement (int)str_replace(',', '',str_replace('.', &#

Time:02-20

i am learning the codebase below form a different developer.i have understood all the sections except this line which defines this variable

$price = (int)str_replace(',', '',str_replace('.', '',number_format($request->get('TvPrice'), 2))); 

what does the TvPrice here might be representing?i was thinking its the model but am not sure.

  public function updatetvPrices(Request $request)
{
 $tv_id       = $request->get('tvPriceId');
    $price       =      (int)str_replace(',', '',str_replace('.', '',number_format($request->get('TvPrice'), 2)));
                        
    $tvPrice = TvPrice::find($tv_id );
    
    $tv->price = $price;
    $tv->save();

}

CodePudding user response:

Whilst it's not entirely possible to say without seeing the full code leading up to this - we can assume $request->get('TvPrice') is a string representation of a price being passed to the code via a GET request.

The assigning code appears to be stripping any commas or decimals from the value of $request->get('TvPrice') and eventually assigning it to an integer.

Why in the same methos it's looking up a TV price and then doing nothing with it, I'm not sure.

CodePudding user response:

'TvPrice' should be price with potentially decimal part in unknown length.

The code limit the decimal length to 2, and then remove the decimal seperator in order to create and integer, which in this case cent to store in DB. We usually prefer store prices as cents to avoid inconcistency.

The reason of removing both '.', and ',' should be localization. User can type 120,5 or 120,50 or 120.5 or 120.50 or maybe 120,5055415. The output will always be 12050.

  • Related