0
$data['results'] = $this->lawmodel->getuser($lastName);
$xp = array("lvl1" => 0, "lvl2" => 256, "lvl3" => 567);
foreach ($data['results'] as $row) {
   $my_xp = $row->points;   // the value is 300
}
for ($i = 0; $i < count($xp); $i++) {
   if ($my_xp >= $xp[$i]) {
      $data['level'] = $i+1;
      break;
   }
   else {
      if (isset($xp[$i+1])) {
         if ($my_xp > $xp[$i] && $my_xp <= $xp[$i + 1]) {
            $data['next'] =  $xp[$i+1],;
            break;
         }
         else {
            $data['next'] =  $xp[$i],
            break;
         }
      }
   }
}

I have a problem the output of $data['level'] = $i+1 is always 1.. I want that it will output the key of an array that the value is equal or greater than $my_xp.

Flow: If the points of the user is 300 it should be at lvl2.

Plss..i need help..im new in php..:(

1 Answer 1

1

Your array

$xp = array("lvl1" => 0, "lvl2" => 256, "lvl3" => 567);

has no integer keys

Try this code:

$data['results'] = $this->lawmodel->getuser($lastName);
$xp = array("lvl1" => 0, "lvl2" => 256, "lvl3" => 567);
$key_prefix = 'lvl';
foreach ($data['results'] as $row) {
   $my_xp = $row->points;   // the value is 300
}
$previous_xp = 0;
foreach ($xp as $lvl => $xp_value) {
if ($my_xp >= $xp_value) {
    $data['level'] = $lvl;
} else {
    if ($my_xp > $previous_xp && $my_xp <= $xp_value) {
        $data['next'] =  $xp_value;
    } else {
        $data['next'] =  $previous_xp;
    }
}
$previous_xp = $xp_value;
}
Sign up to request clarification or add additional context in comments.

2 Comments

what u mean integer keys? @.@
Your array keys are strings = "lvl1", "lvl2", etc, but in your loop you are trying to access array keys 0, 1, 2, etc which don't exist. If possible, change your $xp array structure to something like this: $xp = array(0, 256, 567); That way $xp[0] and $xp[1] will point to the correct index in the array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.