Get user level depending on his/her points number PHP - php

I have a user points system which gives users points depending on some actions like selling a product or add new post etc...
I want to make a smarter PHP function to set a level for the user depending on his/her points.
Here's how I make this:
function get_user_level( $user_id ) {
$user_points = 3515 // Here I get the number of points that user have from the database
if ( $user_point >= 3000 ) {
$level = '5';
} elseif ( $user_point >= 2000 ) {
$level = '4';
} elseif ( $user_point >= 1500 ) {
$level = '3';
} elseif ( $user_point >= 1000 ) {
$level = '2';
} elseif ( $user_point >= 500 ) {
$level = '1';
} else {
$level = '0';
}
echo 'Level:' . $level;
}
The problem that my function seems very bad and not smarter I want to develop my function to upgrade user level for each 1000 point the user has (Making unlimited levels automatically).

You mean something like:
if ($user_points < 2000)
{
$level = floor($user_points / 500);
}
else
{
$level = 4 + floor(($user_points-2000)/1000);
}
Which yields level 0-4 for 0-2000 points and then one additional level every 1000 points.

function get_user_level( $user_id ) {
$user_points = 3515; // Here I get the number of points that user have from the database
$level = intval($user_points/1000);
echo $level;
}

You could use a switch statement:
<?php
function get_user_level( $user_point )
{
switch (true) {
case $user_point >= 3000:
return 5;
case $user_point >= 2000:
return 4;
case $user_point >= 1500:
return 3;
case $user_point >= 1000:
return 2;
case $user_point >= 500:
return 1;
default:
return 0;
}
}
echo get_user_level(3515); // outputs 5
See it here: https://3v4l.org/TmiAH

Related

How do I query incomplete input

I want to transform query string like pending, shipped or cancel to number status.
$q = strtolower($keyword);
if($q == 'pen' or $q == 'pend' or $q == 'pending' ) {
$d = 1;
} elseif($q == 'shi' or $q == 'ship' or $q == 'shipped') {
$d = 2;
} elseif($q == 'can' or $q == 'cancel' ) {
$d = 3;
} else {
$d = 4;
}
$query->whereStatus($d);
Current query working fine but too much or. It's possible to do in shorten way?
str_is(query, stringToSearch) will probably be enough:
if (str_is('pen*', $q)) {
$d = 1;
}
Else you could parse them from arrays:
$pendingArray = ['pen', 'pend', 'pending'];
if (in_array($q, $pendingArray)) {
$d = 1;
}
If these are all the conditions you need, you could always use a switch.
$q = strtolower($keyword);
$d = 4;
switch($q) {
case 'pen':
case 'pend':
case 'pending':
case 'pen':
$d = 1;
break;
case 'shi':
case 'ship':
case 'shipped':
$d = 2;
break;
case 'can':
case 'cancel':
$d = 3;
break;
}
$query->whereStatus($d);
If this needs to be called on a model, it could be saved to a Laravel scope function like so:
on Laravel model
public function scopeSearchStatus($query, $keyword) {
/** All the code above **/
}
Then it can be called cleanly anywhere you'd like:
SomeModel::searchStatus($keyword);
You could also try this:
<?php
$q = strtolower($keyword);
$d = (preg_match('/\b(pen|pend|pending)\b/', $q)) ? 1 : 4;
$d = (preg_match('/\b(shi|ship|shipped)\b/', $q)) ? 2 : 4;
$d = (preg_match('/\b(can|cancel|)\b/', $q)) ? 3 : 4;
$query->whereStatus($d);

Choose a string based on random number

I am working on a bit of PHP and I've come upon a bit of issues.
I am using PHP to randomly choose a number from 1-360. I am trying to compare the answer to a list of value determined by range.
$NumberA = rand(0,180);
$NumberB = rand(0,180);
$NumberC = $NumberA + $NumberB;
if ($NumberC = range(0,21) {
$result = "Orange";
}
elseif ($NumberC = range(22,42) {
$result = "Red";
}
elseif ($NumberC = range(43,63) {
$result = "Blue";
}
//This goes on for a while ...
else {
$result = "Green";
}
echo = $result;
Anytime i do this, the result always assigns the value of "Orange" to $result .
Im sure im doing something wrong here, please help!
First of all, you used just one '=' to compare while it should have been '=='. Second range() generates an array and you cannot compare an integer to an array. Third why generating the range every single time when you can check that $NumberC lies between the minimum and the maximum numbers of the range?
Change your code to:
$NumberA = rand(0,180);
$NumberB = rand(0,180);
$NumberC = $NumberA + $NumberB;
if ($NumberC >= 0 && $NumberC <= 21) {
$result = "Orange";
} elseif ($NumberC >= 22 && $NumberC <= 42) {
$result = "Red";
} elseif ($NumberC >= 43 && $NumberC <= 63) {
$result = "Blue";
} else {
$result = "Green";
}
echo $result;
Shall work. Hope this helps.

Php level and exp system

How can i make a level system where i have 2 table, one for the level and another for amount of exp earned?
I want to be able to manage the different exp requierments myself, like level 2 will need 340exp and level 3 need 450exp. I dont want to set one exp amount and then multiply it. I want to manage the whole system.
I also want to set default level and max level, and give exp directly to the database column without too much problem (for forum posts etc).
I have seen a few questions here but i find them outdated or just not what im looking for.
PS: sorry for bad english and bad explenation.
I found a realy good solution and was able to rewrite it to work with my setup. if anyone is interested i will leave the original link and my edit of it bellow.
my edit:
<?php
// Connect to your database like you normally do, then get any value into the $count variable
$count = $exp;
if($level == 0){
$lvl = 1;
}else{
$lvl = $level;
}
if ($count >= 12800) { $lvl = 10; }
else if ($count >= 6400) { $lvl = 9; }
else if ($count >= 3200) { $lvl = 8; }
else if ($count >= 1600) { $lvl = 7; }
else if ($count >= 800) { $lvl = 6; }
else if ($count >= 400) { $lvl = 5; }
else if ($count >= 200) { $lvl = 4; }
else if ($count >= 100) { $lvl = 3; }
else if ($count >= 50) { $lvl = 2; }
// Render stars or any graphics/images according to dynamic $lvl number
$stars = "";
$i = 1;
while ($i <= $lvl) {
$stars .= "★";
$i++;
}
echo "level $lvl";
?>
Original link:
https://www.developphp.com/video/PHP/Experience-Level-Evaluation-Programming-Tutorial

HTML PHP Math : Fill a progress bar using rank values

I got a progress bar to be filled showing remaining rank points to next level.
Ex: got 25 points and next rank is at 50 points so the bar must to be filled at 50%, if i got 40 point must to be 75% filled etc.
<div class="progress-bar" role="progressbar" aria-valuenow="<?php print $rank; ?>" aria-valuemin="0" aria-valuemax="100" style="width: <?php print get_rank($rank) * next_rank($level) / 2; ?>%;">
The get_rank() function take Rank points and convert to remain points minus $rank value, then I'd pass the $rank value to level() function in order to retrieve the level and finally next_rank() function get the level and return the remaining points.
So the used math is (get_rank($rank) * next_rank($level) / 2) / 10.
Using this return the remaining value ( eg. 19 * 20 / 2 = 500 / 10 = 19% ) print in the width 0.25%, how i can reverse the result to get 99.75% instead of 0.25?
For completeness will paste the complete functions:
<?php
function get_rank($rank) {
if ( $rank >= 5 ) { $rem_point = 20 - $rank; }
if ( $rank >= 20 ) { $rem_point = 50 - $rank; }
if ( $rank >= 50 ) { $rem_point = 100 - $rank; }
if ( $rank >= 100 ) { $rem_point = 500 - $rank; }
if ( $rank >= 500 ) { $rem_point = 1000 - $rank; }
if ( $rank >= 1000 ) { $rem_point = 2500 - $rank; }
if ( $rank >= 2500 ) { $rem_point = 5000 - $rank; }
return $rem_point;
}
function level($rank) {
if ( $rank <= 5 ) { $level = 1; }
elseif ( $rank <= 20 ) { $level = 2; }
elseif ( $rank <= 50 ) { $level = 3; }
elseif ( $rank <= 100 ) { $level = 4; }
elseif ( $rank <= 500 ) { $level = 5; }
elseif ( $rank <= 1000 ) { $level = 6; }
elseif ( $rank <= 2500 ) { $level = 7; }
elseif ( $rank <= 5000 ) { $level = 8; }
return $level;
}
function next_rank($level) {
if ( $level = 1 ) { $next_r = 5; }
elseif ( $level = 2 ) { $next_r = 20; }
elseif ( $level = 3 ) { $next_r = 50; }
elseif ( $level = 4 ) { $next_r = 100; }
elseif ( $level = 5 ) { $next_r = 500; }
elseif ( $level = 6 ) { $next_r = 1000; }
elseif ( $level = 7 ) { $next_r = 2500; }
elseif ( $level = 8 ) { $next_r = 5000; }
return $next_r;
}
?>
Thanks to all who can help.
Replace <?php print get_rank($rank) * next_rank($level) / 2; ?>
by <?php print_r(($rank*100)/(get_rank($rank)+$rank)); ?> should do the job you want.
For function level($rank) if i input level(10) output will be 10 as you are returning $rank without any calculation.

Percentage chances on winning multiple prizes

I'm making a script that handles the percentage chances of winning when the user clicks a button.
With the help of this topic php - Chance of winning. I used the following code:
function winningChance($percentage) {
if($percentage < 1 || $percentage > 100) throw new Exception('Invalid percentage');
global $result;
if(rand(1, 100) <= $percentage) {
$result = 'won';
} else {
$result = 'lost';
}
return $result;
}
echo "you have ".winningChance(50).'!';
Once this script has run, it registers the user name / last name / email and a field called winner with the $result in a SQL database
This works great, however I would like to handle multiple prizes with different percentages of winning chances.
Lets say prize1 have 20% chances of being won,
prize2 30% chances
and prize3 50% chances.
If I use winningChance(20), winningChance(30), winningChance(50) the user will have more chances of winning. How can I handle it so, the win/lost process happens in the same function for multiple prizes?
If I understand you correctly, the chance of winning depends on the price.
function getChanceOfWinning($price)
{
$chances = array(
10 => 20,
20 => 30,
30 => 50
);
if (isset($chances[$price])) {
return $chances[$price];
}
return 0; // <-- default chance
}
function calculateWinningChance($price)
{
$chance = getChanceOfWinning($price);
$calc = rand(1, 100);
if ($calc <= $chance) {
return true;
}
return false;
}
function calculateWinningChances(array $prices)
{
$results = array();
foreach($prices as $price) {
$results[$price] = calculateWinningChance($price);
}
return $results;
}
var_dump(calculateWinningChances(array(10,20, 30,40,700)));
How about this solution ?
function roll( $iChance ) {
$iCursor = rand( 0,99 );
$aModel = array();
while ( count( $aModel ) != $iChance ) {
$iRandValue = rand( 0,99 );
if ( !in_array( $iRandValue, $aModel ) ) {
$aModel[] = $iRandValue;
}
}
return in_array( $iCursor, $aModel );
}
Edit: More perfomance:
function roll( $iChance ) {
$iChance = ceil( ( $iChance > 100 ) ? 100 : (int)$iChance);
$iCursor = rand( 0, 99 );
$aModel = range( 0, 99 );
shuffle( $aModel );
return in_array( $iCursor, array_slice( $aModel, 0, $iChance ) );
}
If I understood correctly, you want to have multiple winning calculations for each user at the same time, independent of one another. There are numerous ways to do this. Modify your function so that you can pass an associative array as an argument, for example.
The array would be a map of price=>percentage values and then you do the calculations for each pair.
You'd also need to modify your result variable in an array, and on each pass just push the result of the calculation into it. You can also use an associative array here to show price=>won/lost. After you looped through all the pairs and filled up the result variable with the results, just return the variable.
Based on your last comment, this is what you need:
function winningChance($percentage) {
foreach($percentage as $p) {
if($p < 1 || $p > 100)
throw new Exception('Invalid percentage');
}
if (count($percentage) != 3)
throw new Exception('Three prizes need to be defined');
$rand = rand(1, 100); // generate the random chance only once!
if ($rand <= $percentage[0])
$result = 'won first prize';
elseif ($rand <= $percentage[1])
$result = 'won second prize';
elseif ($rand <= $percentage[2])
$result = 'won third prize';
else
$result = 'lost';
return $result;
}
And call the function like this:
//the array contains probability percentages for the first, second and third place respectively
$res = winningChance( array(20, 30, 50) );
echo "You have $res!";
// write $res to the db here
tweak your function code like,
instead of,
if(rand(1, 100) <= $percentage) {
$result = 'won';
} else {
$result = 'lost';
}
to,
if(rand(1, 100) >= 50) {
$result = 'won third price';
} else if(rand(1, 100) >= 30) {
$result = 'won second price';
}
else if(rand(1, 100) >= 20) {
$result = 'won first price';
}
else
{
$result='lost';
}

Categories