Since you’re new to PHP, I’m not trying to show you complicated ways for your currency converter. Right now you need to learn the basics and shouldn’t focus on making your code concise by using advanced strategies. Your code is a nice one and will work perfectly if two adjustments are made:
- Use
==
(comparison operator) instead of=
(assignment operator) when you compare two values. - Use an
if/else if/else
structure instead of a series of disjointedif
structures.
Now your code becomes:
<?php
$amount_input = filter_input(INPUT_POST, 'amount_input');
$currency1 = filter_input(INPUT_POST, 'currency1');
$currency2 = filter_input(INPUT_POST, 'currency2');
if ($currency1 == "CAD" AND $currency2 == "CAD")
{
$amount_output = $amount_input*1.0;
}
else if ($currency1 == "CAD" AND $currency2 == "EUR")
{
$amount_output = $amount_input*0.624514066;
}
else if ($currency1 == "CAD" AND $currency2 == "GBP")
{
$amount_output = $amount_input*0.588714763;
}
else if ($currency1 == "CAD" AND $currency2 == "USD")
{
$amount_output = $amount_input*0.810307;
}
else if ($currency1 == "EUR" AND $currency2 == "CAD")
{
$amount_output = $amount_input*1.601244959;
}
else if ($currency1 == "EUR" AND $currency2 == "EUR")
{
$amount_output = $amount_input*1.0;
}
else if ($currency1 == "EUR" AND $currency2 == "GBP")
{
$amount_output = $amount_input*0.942676548;
}
else if ($currency1 == "EUR" AND $currency2 == "USD")
{
$amount_output = $amount_input*1.2975;
}
else if ($currency1 == "GBP" AND $currency2 == "CAD")
{
$amount_output = $amount_input*1.698615463;
}
else if ($currency1 == "GBP" AND $currency2 == "EUR")
{
$amount_output = $amount_input*1.060809248;
}
else if ($currency1 == "GBP" AND $currency2 == "GBP")
{
$amount_output = $amount_input*1.0;
}
else if ($currency1 == "GBP" AND $currency2 == "USD")
{
$amount_output = $amount_input*1.3764;
}
else if ($currency1 == "USD" AND $currency2 == "CAD")
{
$amount_output = $amount_input*1.234100162;
}
else if ($currency1 == "USD" AND $currency2 == "EUR")
{
$amount_output = $amount_input*0.772200772;
}
else if ($currency1 == "USD" AND $currency2 == "GBP")
{
$amount_output = $amount_input*0.726532984;
}
else if ($currency1 == "USD" AND $currency2 == "USD")
{
$amount_output = $amount_input*1.0;
}
?>
Happy coding!