Home > database >  How to do $string = if(in range)?
How to do $string = if(in range)?

Time:09-27

Basically I'm trying to achieve this:

// generating a random number
$randomid = rand(261, 270);
//if range is between numbers, assign strings
$verticalaa = if ($randomid >= 261  && $randomid <= 265);
$verticalbb = if ($randomid >= 266  && $randomid <= 270);
//echo the range string name
echo 'random range is in' . $verticalaa . '' . $verticalbb . '';

In the end I want to echo the name of matching range.

If the number is, let's say, 262, it would echo verticalaa.

I hope it's possible to understand what I'm after.

My head is like a balloon now after hours of coding.

Need help.

CodePudding user response:

Probably an easier way to this would be ternary and assign 1 variable.

$randomid = rand(261, 270);
$var = in_array($randomid, range(261, 265)) ? 'between 261 and 265' : 'between 266 and 270';
echo $var;

CodePudding user response:

For readability purpose for long lists you can use switch operator in this way:

switch (true)
{
    case $a > 100: $result = 'aaa'; break;
    case $a >  90: $result = 'bbb'; break;
    case $a >  80: $result = 'ccc'; break;
    
    // ...
    
    case $a >   0: $result = 'zzz'; break;
}

At the same time, your question looks like a classic XY problem and what you ask is not what you need.

  •  Tags:  
  • php
  • Related