1

I'm trying to get the inverse of the number thats POSTED from a form.

<select name="inverse_num">
<option value="2">2 </option>
<option value="1">1 </option>
<option value="1/2">1/2 </option>
<option value="1/3">1/3 </option>
</select>

In the php file which gets the value, say "1/2",

$my_inverse=1/($_POST[inverse_num]);  // returns 1 , but..
$my_inverse=1/(1/2);  // returns 2, which is required.

Why does this happen..coz logically I'm posting the same value. Please suggest.

Sabharish
  • 101
  • 3
  • 12

4 Answers4

3
  • You can only post text from a form.
  • PHP doesn't care if a variable contains a string or a number, it will convert between them.
  • PHP won't resolve text that looks like equations.

You could do something along the lines of:

function simple_fractions ($value) {
    if (is_numeric($value)) {
            return $value;
    }
    preg_match('/^(\d+)\/(\d+)$/', $value, $matches);
    if ($matches[1] && $matches[2]) {
            return $matches[0] / $matches[1];
    }
    if ($matches[1] == 0) {
            return 0;
    }
    return false;
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

Your two expressions:

$my_inverse=1/($_POST[inverse_num]);   // array keys shall be quoted
$my_inverse=1/(1/2); 

Are actually:

$my_inverse=1/"1/2"; 
$my_inverse=1/(1/2); 

Which does explain the outcome.

If you were to send the string 0.5 instead, then PHP would process it as expected, btw.

mario
  • 144,265
  • 20
  • 237
  • 291
1

Quentin has a possible solution.

However, another one is even better in my opinion:

<select name="inverse_num">
<option value="a">2 </option>
<option value="b">1 </option>
<option value="c">1/2 </option>
<option value="d">1/3 </option>
</select>

Then in your submission script:

if($_POST['inverse_num'] == 'a'){
  $value = 2;
}elseif($_POST['inverse_num'] == 'b'){
  $value = 1;
}elseif($_POST['inverse_num'] == 'c'){
  $value = 1/2;
}elseif($_POST['inverse_num'] == 'd'){
  $value = 1/3;
}

Etc....

Nothing complex about this method.

Shackrock
  • 4,601
  • 10
  • 48
  • 74
  • Assuming that the values are always the same, or at most modified from this code... – Chaim Oct 18 '11 at 14:11
  • @ChaimChaikin - his code is using static HTML with drop down boxes... aka they are the only options. That's why this is such an easy solution... The above one works though. – Shackrock Oct 18 '11 at 22:08
  • True, sometimes though, people only post the static HTML even if the code is generated dynamically. – Chaim Oct 19 '11 at 10:57
0

What about posting decimals instead of fractions? e.g. 0.5

Chaim
  • 2,109
  • 4
  • 27
  • 48