I'm trying to split a line of PHP up, the reason being I don't actually always need some of the code and so that I can reuse parts of it.
The main reason I'm doing this is because the currency I get shows more digits for some currencies eg 1.2562 instead of 1.25, so I want to use the substr function only on certain GET's and be able to modify it for other GET's.
symbol is always required, substr isn't, $converter always required, end part of substr isn't however it can change, new currency is required.
$symbol[2] . substr(($converter->convert($defaultCurrency, $newCurrency) * 1), 0, 4) . " <b>" .$newCurrency. "</b>";
I've tried doing this with explode, however I'm not entirely sure how to do it as I have never really had to split anything up before so I'm a little puzzled on how to go about it.
Once the code has gone through the GET checking which is the current one set, I want it to grab the specified split up code pieces and then output it.
Put your code in a function like this:
function formatCurrency($symbol, $converter, $defaultCurrency, $newCurrency, $factor=1.0, $suffix="", $substrChars=0) {
if($substrChars>0) {
return $symbol . substr(($converter->convert($defaultCurrency, $newCurrency) * $factor), 0, $substrChars) . $suffix . " <b>" . $newCurrency. "</b>";
} else {
return $symbol . ($converter->convert($defaultCurrency, $newCurrency) * $factor) . $suffix . " <b>" . $newCurrency. "</b>";
}
}
If you call it without the $substrChars
parameter, it will omit the substr()
call, otherwise it will strip all but the first $substrChars
characters:
if( $_GET['currency'] === "GBP" ){
$newCurrency = $_GET['currency'];
$string = formatCurrency($symbol[1], $converter, $defaultCurrency, $newCurrency, 2.0, ".00", 0);
} elseif( $_GET['currency'] === "USD" ){
$newCurrency = $_GET['currency'];
$string = formatCurrency($symbol[2], $converter, $defaultCurrency, $newCurrency, 1.0, "", 4);
}
This solution is very readable because you immediately see the difference between the two branches in the conditional statement.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.