简体   繁体   中英

How to get previous and next keys of a php array?

Below is my array that I want to create if conditions in the type of

if (($variable >=2) && ($variable <3)) { echo '10'; }

However to create this I need to play with previous and next items of the array. How can I achieve this result?

Array
(
    [2] => 10
    [3] => 14
    [4] => 15
    [5] => 16
    [8] => 17
    [14] => 18
    [51] => 19
    [94] => 20
)


   foreach($the_final_array as $key => $value){
echo $key;
echo $value;
echo $previous_key;
echo $nect_key;
}

You can't use next() and prev() on foreach because it works with a copy of the array, and you don't have a nice sequential index of 0,1,2,3... so you can't do simple key addition/subtraction, but you can if you manage the cursor position yourself.

Using a do/while loop, you can manually advance with next() and then go backwards forwards, taking into consideration that if you rewind or advance too far, you break the array cursor.

$array = array( 2=>10, 3=>14, 4=>15, 5=>16, 8=>17, 14=>18 );

$value = current( $array );

do
{

  echo 'current-key: ' . key( $array ) . PHP_EOL;
  echo 'current-value: ' . $value . PHP_EOL;

  // PREV
  if( ( $prev = prev( $array ) ) === false )
  {
    echo 'prev-key: N/A' . PHP_EOL;
    echo 'prev-value: N/A' . PHP_EOL;
    reset( $array );  // Restore cursor
  }
  else
  {
    echo 'prev-key: ' . key( $array ) . PHP_EOL;
    echo 'prev-value: ' . $prev . PHP_EOL;
    next( $array ); // Restore cursor
  }

  // NEXT
  if( ( $next = next( $array ) ) === false )
  {
    echo 'next-key: N/A' . PHP_EOL;
    echo 'next-value: N/A' . PHP_EOL;
    end( $array ); // Restore cursor
  }
  else
  {
    echo 'next-key: ' . key( $array ) . PHP_EOL;
    echo 'next-value: ' . $next . PHP_EOL;
    prev( $array ); // Restore cursor
  }

  echo PHP_EOL;

} while( $value = next( $array ) );

This will print blocks like the following

// current-key: 2
// current-value: 10
// prev-key: N/A
// prev-value: N/A
// next-key: 3
// next-value: 14
//
// current-key: 3
// current-value: 14
// prev-key: 2
// prev-value: 10
// next-key: 4
// next-value: 15
//
// current-key: 4
// current-value: 15
// prev-key: 3
// prev-value: 14
// next-key: 5
// next-value: 16

Maybe I'm wrong but from the first part of your question I think you don't need to get the previous or the next key/item of the array.

I want to create if conditions in the type of

 if (($variable >=2) && ($variable <3)) { echo '10'; } 

It seems you have some intervals and you want to know what interval contains the value of $variable and print a different value for each interval.

The easiest solution for this is to use a set of cascaded if statements:

if ($variable < 2) {                 // $variable < 2
    echo('N/A');
} elseif ($variable < 3) {           // 2 <= $variable < 3
    echo(10);
} elseif ($variable < 4) {           // 3 <= $variable < 4
    echo(14);
} elseif ($variable < 5) {           // 4 <= $variable < 5
    echo(15);
} elseif ($variable < 8) {           // 5 <= $variable < 8
    echo(16);
} elseif ($variable < 14) {          // 8 <= $variable < 14
    echo(17);
} elseif ($variable < 51) {          // 14 <= $variable < 51
    echo(18);
} elseif ($variable < 94) {          // 51 <= $variable < 94
    echo(19);
} else {                             // 94 <= $variable
    echo(20);
}

This strategy works fine and it is easy to read and understand.

However, it doesn't work when the list of ranges (and their values) is not known when the code is written (it is loaded from the database, for example).

In such a situation, a simple foreach loop can be used to iterate over the list an identify the correct range.

function getValue($input)
{
    $limits = array(
        2 => 10,
        3 => 14,
        4 => 15,
        5 => 16,
        8 => 17,
        14 => 18,
        51 => 19,
        94 => 20,
    );

    foreach (array_reverse($limits, TRUE) as $key => $value) {
        if ($key <= $input) {
            return $value;
        }
    }

    return 'N/A';
}


echo(getValue(2));              # 10
echo(getValue(6));              # 16
echo(getValue(25));             # 18
echo(getValue(51));             # 19
echo(getValue(100));            # 20

The function array_reverse() returns an array with elements in the reverse order. Passing TRUE as its second argument makes it preserve the key/value association of the original array.

The foreach loop compares the input value with the keys of the array in reverse order. When a key that is smaller than the input value is found, it is the lower range bound and the associated value is returned.

If the input value is smaller than any key of the array then it means $variable < 2 and it returns N/A because this case is not described in the question.

If you need to run this code many times and/or the list of ranges is large then it's better to have the list of bounds sorted descending and remove the call to array_reverse() (use just $bounds instead).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM