Jump to content

Recommended Posts

Hello altogether,

 

I hope you can help me.

I got some fields in a form and one of these is that I want to give the user the opportunity to type in a fraction instead of a decimal digit.

Input for example would be: 14/3 or 26/23 etc. Now I got the problem with devision by zero e.g. 12/0 and it seems that I made a mistake with the if query, but I dont find it. Could you please help me? This is the code:

while(strpos($insert, "/")!=false) {
	preg_match_all("/([\d]+)\/([\d]+)/", $insert, $var);


	if (((int)$var[2][0]) == 0) {
		$var = "division by zero";
	}
	else
	{
		$insert=str_replace($var[1][0].'/'.$var[2][0], (int)$var[1][0]/(int)$var[2][0], $insert);
	}
}

...

if ($var != "division by zero") {
	--> calculating with $insert and output into $var
	}
	
echo $var;

The output of $var should be a decimal digit or "devision by zero".

Please note: Everything works fine if there is no devision by zero. (like 16/0 for example)

 

Thank you a lot!

Kind regards!

Link to comment
https://forums.phpfreaks.com/topic/287613-if-statement-with-arrays-doesnt-work/
Share on other sites

Hi,

 

that code is weird. Is there any reason why you are not simply using preg_replace()

 

Your current code has two problems: If there's a division by 0, you're not doing anything with the input. That means your loop runs forever. The second problem is that you keep overwriting $var (which is also a really crappy name for a variable).

 

I suggest you use preg_replace() and fix your variable names. You also need to be aware that replacing fractions with floats will lead to “strange” results, because even simple fractions like 1/10 cannot be expressed as floating point numbers. This will be very confusing for the users.

Edited by Jacques1

Hello @Jacques1, thank you a lot for your response! That helped me.

I changed the variable names.

 

What could I do with the input in order to get no loop?

I would like to check everything behind the / if it is zero.

 

For example:

1/20 -->ok

2/0 --> wrong

2/01 --> ok

 

I don't know if I unterstood your last paragraph correct. But the output of floats instead of fractions shouldnt be a problem in this case.

 

Thank you a lot!

Kind regards!

You wouldn't need to a loop at all, use preg_replace_callback and write a function to do the conversion

$insert = preg_replace_callback("/([\d]+)\/([\d]+)/m",  function($m) {

                                                            list(, $num1, $num2) = $m;

                                                            if($num1 == 0 || $num2 == 0)
                                                                $dec = 'division by zero';
                                                            else
                                                                $dec = $num1 / $num2;

                                                            return $dec;
                                                        }
                                                    , $insert);

What could I do with the input in order to get no loop?

 

When you use preg_replace() as suggested, there's no risk of running into an infinite loop.

 

If you're asking how to deal with divisions by 0, well, that's up to you. You can reject the input altogether or replace the invalid fractions with error messages or whatever.

 

 

 

I don't know if I unterstood your last paragraph correct. But the output of floats instead of fractions shouldnt be a problem in this case.

 

That depends on what you wanna do with the numbers and on your audience. If your users get weird results for seemingly simple math operations, they will wonder what the hell is going on (unless they're familiar with IEEE floating point numbers).

Thank you a lot for your excellent advices!

@Jacques1: Yes, I would like to output an error message!

@Ch0cu3r: I tried to use your version, but I get an error for the third line ($userdiv = preg_re...): <br /><b>Warning</b>:  Wrong parameter count for preg_replace_callback() in <b>server/script.php</b> on line <b>59</b><br />

 

This is the code now:

while(strpos($userdiv, "/")!=false) {
preg_match_all("/([\d]+)\/([\d]+)/", $userdiv, $sta);
$userdiv = preg_replace_callback("/([\d]+)\/([\d]+)/", $userdiv);

function division($m) {
list(, $num1, $num2) = $m;
if($num1 == 0 || $num2 == 0) {
$sta = 'division by zero';
}
else
{
$userdiv=str_replace($sta[1][0].'/'.$sta[2][0], (int)$sta[1][0]/(int)$sta[2][0], $userdiv);
return $sta;
}
}
}

Have I done anything wrong with preg_replace_callback?

Thank you very much!

 

Ok, I exactly used your code:

while(strpos($insert, "/")!=false) {
$insert = preg_replace_callback("/([\d]+)\/([\d]+)/m",  function ($m) {

                                                            list(, $num1, $num2) = $m;

                                                            if($num1 == 0 || $num2 == 0)
                                                                $dec = 'division by zero';
                                                            else
                                                                $dec = $num1 / $num2;

                                                            return $dec;
                                                        }
                                                    , $insert);
}

But I always get this error:

<br /><b>Parse error</b>:  syntax error, unexpected T_FUNCTION in <b>server/script.php</b> on line <b>58</b><br />

Line 58 is this one: $insert = preg_replace_callback("/([\d]+)\/([\d]+)/m", function ($m) {

The same when I try it with: $insert = preg_replace_callback("/([\d]+)\/([\d]+)/m", function divcalc($m) {

 

Do you detect the mistake?

Thank you a lot!

Two things:

 

You still haven't replaced your code with Ch0cu3r's. You've merged his code into your while loop, which simply doesn't work. No while loop, no strpos(), just preg_replace_callback().

 

The syntax error means that you're running some old PHP version which doesn't support anonymous functions yet. You need a different approach then:

 

<?php

function replace_fraction($matches)
{
    // replacement stuff goes here
}

$insert = preg_replace_callback("/([\d]+)\/([\d]+)/m", 'replace_fraction', $insert);

The current check makes no sense, though. Dividing 0 is perfectly fine and simply yields 0. What you musn't do is divide by 0. So you only check the denominator, not the numerator.

 

And this doesn't throw any error message. It silently replaces the invalid fractions with the string "division by zero". Not sure if that's what you want.

 

I was actually hoping you would write the code yourself and learn from it instead of copypasting other peoples' solutions. But after Ch0cu3r has jumped in, I guess we can forget about that.

Edited by Jacques1
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.