Jump to content

Recommended Posts

<?php
if ($load_dock=='Load_Dock_Yes')
{
$str2 = $rate;
list ($str2) = explode('.',ltrim($str2,'$'));
$str=$str2*1.13;
}
?>
<?php
if ($load_dock!='Load_Dock_Yes')
{
$str2 = ($rate+75);
list ($str2) = explode('.',ltrim($str2,'$'));
$str=$str2*1.13;
}
?>

 

What the did I do wrong here?

Link to comment
https://forums.phpfreaks.com/topic/112917-problem-with-if-statement/
Share on other sites

That code above is much more efficient than mine but the result is still the same. It is simply adding 75 to nothing if the results is not Load_Dock_Yes. In the else area it seems to be marking the $rate as nothing, not zero, just non-existent. Like it has it in the first part of the if statement and it losses it half way through.

i think your main issue is type conversion.  $rate starts as a string, but you want to process it like a float.  To convert it to a float, you started off correctly with the ltrim to ditch the '$'.  Once that is gone, we need to convert $rate into a number.  This is called type casting and in php it is done with (type):

 

So the first part of the code is :

$rate_num = (float)ltrim($rate,'$');

 

There I stripped the $ off the string, converted it to a float.  Those steps were common to both if blocks, so I pulled them out.  Now all we need to do is check the value of load_dock and add 75 and then multiply by 1.13.

 

if ($load_dock=='Load_Dock_Yes') $rate_num += 75;

$rate_num *= 1.13;

;

 

So if $load_dock == 'Load_Dock_Yes' we add 75.  If it doesn't, nothing happens.  Then we finally multiply the number by 1.13.  The += is short hand for $rate_num = $rate_num  + 75.  If you want to be technical, it is also a faster (computationally) way of doing it as well.  Same for the *=.

 

so the overall code is:

<?
$rate_num = (float)ltrim($rate,'$');

if ($load_dock=='Load_Dock_Yes') $rate_num += 75;

$rate_num *= 1.13;
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.