user5641678
user5641678

Reputation: 35

query with IF not working

Hi I have some variables which are calculated with API's in an early script but successfully return the value $TotalDistance (based on postcode to postcode driving distances).

I have added a checkbox to tick when it is a return journey, the idea is that it then doubles the distance, this is my query.

if($values['Return']>0) $TotalDistance=2*$TotalDistance; else $TotalDistance=$TotalDistance;

However the result is still returning as a single (x1) value even if checkbox is ticket? Why

Upvotes: 1

Views: 36

Answers (1)

Chris
Chris

Reputation: 1128

I'm assuming this is a HTML form and $values is either a reference to, or built from $_POST.

When submitting a checkbox in an HTML form, there are two possible outcomes:

  1. Unchecked - doesn't get submitted and won't be part of the array
  2. Checked - the VALUE of the checkbox gets submitted

Example:

<input type="checkbox" name="Result" value="MyResultValue" />
<input type="hidden" name="HidValue" value="OtherValue" />

Would yield this when unchecked:

array (size=1)
    'HidValue' => string 'OtherValue' (length=10)

And when checked:

array (size=2)
    'Result' => string 'MyResultValue' (length=13)
    'HidValue' => string 'OtherValue' (length=10)

So, to check if it is checked (I like to include a validation check to make sure the value wasn't changed) do something like this:

$values = $_POST; //again I'm assuming something like this is happening
if( isset($values['Result']) && $values['Result'] == 'MyResultValue' )

If you don't care about the validation - just use the isset.

Upvotes: 1

Related Questions