 Bajwa kapoor - 4 years ago 125
PHP Question

# Save me from writing 500 lines of if/else statements in PHP?

I am in a big trouble,Basically i am learning PHP
Me and my friend doing a mini project that.How a Person is popular in his city.

My situation
How the algorithm should work like
If a person "mark" has 500 friends in his city out of 500,000.

``````(500/500,000)*50,000 = 5
``````

So 5 in 50,000 people Know him right.

But When friends count increase the 50,000 should decrease

like:-

If "sam" has 1000 friends then

``````(1000/500,000)*25000 = 5
``````

So
`5`
in
`25000`
people know his name

Yes we could implement this in
`if/else`
condition
If so then i have to write 500 lines of code.

Is there is a another way to do this in PHP.

Help !

``````<?php
\$totalfriends = 100;
\$totali = 5000000;
\$name = "Sam";

if (\$totalfriends >= 100 && \$totalfriends <= 499 ) {
\$r = (\$totalfriends/\$totali)*50000;
echo  round(\$r),' ',"in 50K People on City regonize this Profile";
}else if (\$totalfriends >= 500 && \$totalfriends <= 999) {
\$r = (\$totalfriends/\$totali)*25000;
echo  round(\$r),' ',"in 25K People on City know".\$name;
}else{
echo "";
}
?>
`````` Anonymous

is this what you are looking for?

``````foreach([100, 500, 543, 1000, 5000, 51000, 500000] as \$my_friends)
echo '5 in '. getScoreOf(\$my_friends) . "<br>";

function getScoreOf(\$my_friends){
\$of = 5;
\$total = 5e5; //that's 500,000 ;)
\$step = 100; //minimum step, so output is not "4604" but "4600"
\$out_of = \$total / \$my_friends * \$of;
return \$out_of > \$step? round(\$out_of / \$step) * \$step: round(\$out_of);
}
``````

run it in sandbox

edit: solution merged with original code

``````<?php
\$of = 5;
\$totalfriends = 100;
\$name = "Sam";
echo \$of ." in ". getScoreOf(\$of, \$totalfriends) ." people in city know ". \$name;

function getScoreOf(\$of, \$my_friends){
\$total = 5e6; //that's 5,000,000 ;)
\$step = 100; //minimum step, so output is not "4604" but "4600"
\$out_of = \$total / \$my_friends * \$of;
return \$out_of > \$step? round(\$out_of / \$step) * \$step: round(\$out_of);
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download