Reputation: 329
I have a simple php scrip to converts a csv file into a different layout which works fine, but I want to add a rule that if the value is negative then output 0 instead. Can someone point me in the right direction on how to do it ( code below with the line where the rule to be applied marked)
Thanks
<?php
function twoDecs($num_in)
{
$split = explode('.', $num_in);
if(!isset($split[1]))
$num_out = $num_in . '.00';
else{
if(strlen($split[1])<2)
$num_out = $split[0] . '.' . $split[1] . '0';
else
$num_out = $split[0] . '.' . $split[1];
}
return $num_out;
}
function array_to_csv($array_in)
{
$csv_content = 'sku;qty;special_price;price;is_in_stock
';
$lines = explode('
', $array_in);
for($i=0;$i<count($lines);$i++)
{
$line = explode(',', $lines[$i]);
if(trim($line[1])!='')
{
$csv_content .= trim($line[1]) . ';';
$csv_content .= trim($line[8]) . ';'; <----- line where rule to be added
$csv_content .= twoDecs(trim($line[6])) . ';';
$csv_content .= twoDecs(trim($line[7])) . ';';
$csv_content .= '1' . '
';
}
unset($line);
}
$now = date('YmdHis');
file_put_contents('files/ProductUpdateRF.csv', $csv_content);
echo '<a href="files/ProductUpdateRF.csv"> Download reformatted CSV here. </a>';
}
?>
Upvotes: 0
Views: 959
Reputation: 45
if ($line[8]<0)
$csv_content .= 0 ';';
else
$csv_content .= trim($line[8]) . ';';
Upvotes: -1
Reputation: 4218
Here you go:
$csv_content .= max(trim($line[8]), 0).';';
This uses Max which returns the highest value. In this case, if the first parameter's value is less than zero (2nd parameter), MAX will return zero
Upvotes: 2
Reputation: 5252
Try out:
$csv_content .= (intval(trim($line[8])) < 0 ? "0" : trim($line[8])) . ';';
This uses the ternary operator which is a shorthand if()
.
Upvotes: 2
Reputation: 3737
To keep the code readable and to solve your problem you can use the ternary (shorthand) operator ?:
$csv_content .= (float) $line[8] < 0 ? 0 : trim($line[8]) . ';';
Upvotes: 0