Boneheaded PHP math question

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.
LVL 2
erzoolanderAsked:
Who is Participating?
 
Radek BaranowskiFull-stack Java DeveloperCommented:
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

0
 
Radek BaranowskiFull-stack Java DeveloperCommented:
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)
0
 
Radek BaranowskiFull-stack Java DeveloperCommented:
yeah, ceil() will just do!

http://php.net/manual/en/function.ceil.php
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
KimputerCommented:
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

0
 
KimputerCommented:
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.
0
 
erzoolanderAuthor Commented:
Gracias :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.