Question

I`m stucked on a php code and my question is:

I`m working with php if and elseif to show something like this below:

<?php 
   $test_a = 0 to 10; (My problem)
   $test_b = 11 to 20; (My problem)
   $test_c = 21 to 30; (My problem)
   $test = 50; (random value) 
   $something = 12;
   $something_b = 5;
   $something_c = 15;
?>

<?php
 if($test>=$test_a){
 echo $something;
 }elseif ($test=<$test_b) {
 echo $something_b;
 }elseif (test=<$test_c) {
  echo $something_c;
 }
 ?>

My question is how do I work with range using if/elseif.

Thanks!

Was it helpful?

Solution

That obviously is not valid syntax. This really is just a basic if/else statement:

if($test>=0 && $test <=10){
 echo $something;
 }elseif ($test>=11 && $test <=20) {
 echo $something_b;
 }elseif ($test>=21 && $test <=30) {
  echo $something_c;
 }

Just check of $test is greater than or equal to value 1 or less than or equal to value 2. If not, move on to your next if statement.

OTHER TIPS

Set your variables to the top of each range:

$test_a = 10;
$test_b = 20;
$test_c = 30;

if ($test <= $test_a) {
    echo $something;
} elseif ($test <= $test_b) {
    echo $something_b;
} elseif ($test <= $test_c) {
    echo $something_c;
}

If you have lots of cases, it may be better to create an array and use a loop:

$tests = array (array ('limit' => 10, 'message' => $something),
                array ('limit' => 20, 'message' => $something_b),
                array ('limit' => 30, 'message' => $something_c)
               );
foreach ($tests as $curtest) {
    if ($test <= $curtest['limit']) {
        echo $curtest['message'];
        break;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top