We help IT Professionals succeed at work.

Boneheaded PHP math question

erzoolander
erzoolander asked
on
Let's say you wanted to figure out how many cars a group needs to rent.

$capacity is the number of people the car can hold
$people is the number of people in your group

My first thought on how to approach it would be to do something like

while ($people > 0) {
$cars ++;
$people = $people - $capacity;
}

That way it just kinda iterates up the number of cars as groups.  Say car capacity is 5... If there's one person, it only occurs once.  If there's 6 people, it cycles twice, 2 cars...etc.

Is there a better way you think of approaching that?  Just feels kinda sloppy to me doing it that way.
Comment
Watch Question

Radek BaranowskiFull-stack Java Developer

Commented:
you might use modulo
if ($people % $capacity ==0)
{
$cars = $people/$capacity
}
else
{
$cars= ceil($people/$capacity);
}

Open in new window


ot just use

ceil($people/$capacity)
Radek BaranowskiFull-stack Java Developer

Commented:
yeah, ceil() will just do!

http://php.net/manual/en/function.ceil.php

Commented:
For simple math, the while loop makes it harder to read what you exactly mean:

<?php

$people = 11;
$cars = 5;
if (($people % $cars) > 0) {
echo (floor($people / $cars) + 1);

}

else {
echo (floor($people / $cars));
}

?>

Open in new window

Full-stack Java Developer
Commented:
sample code:

<?php

echo "5 people: " . ceil(5/5)." car(s)";
echo "<br>";
echo "7 people: " . ceil(7/5)." car(s)";

?>

Open in new window

Commented:
I used the wrong titles btw (cars  should be capacity, echo is cars). And that's besides the fact that the other expert's solution is neater.

Author

Commented:
Gracias :)