Skip to content
Advertisement

Setup a whole range of PHP if statements for code to pull from

I have a whole bunch of values, that need to correspond to some other values. I’ve so far setup an array as per the below:

    $result = array(
            1 => 'Red',
            2 => 'Orange',
            3 => 'Yellow',
            4 => 'Green'
    );

I also have a variable, $input that provides a number value.

I need to figure out a way to say something like:

<?php if $input = any of the values in the array, then display its corresponding colour. 

My array list will end up having hundreds of values in it, so if there is a much better way to achieve this I’m all ears. It just must be in PHP.

How could this best be achieved? Many thanks for any help in advance!

Advertisement

Answer

This can be accomplished quite easily using the isset function:

<?php

$result = array(
    1 => 'Red',
    2 => 'Orange',
    3 => 'Yellow',
    4 => 'Green'
);

$input = 3;

if (isset($result[$input]))
    echo $result[$input] . PHP_EOL;

To find within a range:

$result = [
    '1-2' => 'Red',
    '2-5' => 'Orange',
    '6-9' => 'Yellow',
    '10-20' => 'Green'
];

$input = 8;

foreach ($result as $range => $colour) {
    $split = explode('-', $range);
    if ($input >= $split[0] && $input <= $split[1]) {
        echo $colour . PHP_EOL;
    }
}

Note: This code would blow up if you accidentally had ranges overlap in some way.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement