Jump to content


Photo

PHP Division By Zero?


  • Please log in to reply
4 replies to this topic

#1 ShoeLace1291

ShoeLace1291

    Advanced Member

  • Members
  • PipPipPip
  • 396 posts

Posted 27 October 2011 - 04:18 AM

So, this is something that I've been wondering for a while now... say you have two variables that you need to divide to find a certain percentage and one happens to be zero... why does PHP feel the need to return a warning saying there was a division by zero?  why not just return the number zero since anything that's divided by zero always results in zero anyway?  Just a random thought.
Posted Image

#2 jotorres1

jotorres1

    Advanced Member

  • Members
  • PipPipPip
  • 85 posts

Posted 27 October 2011 - 05:20 AM

That not true, division by zero is NOT equal to zero.  Just basic math.  Example, you have 3 / 0 != 0 because  0 x 0 != 3.  You get the point.  In which case, in PHP you can use the Error Suppression Operator, something like this.

$a = @(25/0);

Using the '@' Operator, the error is suppressed.
The slowest component sits behind the keyboard.
PHP Beginners Jotorres Web Development
Posted Image

#3 Kieran Menor

Kieran Menor

    Advanced Member

  • Members
  • PipPipPip
  • 179 posts
  • LocationDenmark

Posted 27 October 2011 - 05:24 AM

Or even better, you should do a check to see if your divisor is zero so you can handle the situation correctly.

#4 jotorres1

jotorres1

    Advanced Member

  • Members
  • PipPipPip
  • 85 posts

Posted 27 October 2011 - 05:27 AM

Yea, these division by zeros are common questions asked in any programming job interviews.  Division by zero should always be handled no matter the language.
The slowest component sits behind the keyboard.
PHP Beginners Jotorres Web Development
Posted Image

#5 The Little Guy

The Little Guy

    Advanced Member

  • Members
  • PipPipPip
  • 6,676 posts

Posted 27 October 2011 - 10:20 AM

$number = 100;
if($me == 0)
	$result = 0;
else
	$result = $number / $me;
echo $result;

phpLive - A powerful library that implements many common tasks to make php programming faster. Supports extensions and plugins. Current version: 1.0.0-Alpha
Twitter: http://twitter.com/phpsnips
http://dreamhost.com (promo code: 8RN4)
$30 off 1 year of hosting
$40 off 2 years of hosting




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com