0

How to get next value from match value in loop? I need '1010-1040' key in array.

<?php

$arr = Array
(
    '0900-0930' => 0,
    '0935-1005' => 0,
    '1010-1040' => 0,
    '1045-1115' => 0
);


$matchVal = '0935-1005';

foreach ($arr as $key => $value) {
    
    if($matchVal == $key){
        echo $key.'<br />';
    }
    echo next($arr); 
}
?>
jps
  • 20,041
  • 15
  • 75
  • 79
Karnail Singh
  • 116
  • 1
  • 12
  • Related: [PHP - fast way to get previous array elements before specific key](https://stackoverflow.com/q/47503007/2943403) – mickmackusa Feb 01 '23 at 21:42

3 Answers3

1
      <?php 
        $arr = Array
        (
            '0900-0930' => 0,
            '0935-1005' => 0,
            '1010-1040' => 0,
            '1045-1115' => 0
        );
        $keys = array_keys($arr);
        $matchVal = '0935-1005';
        $matched = array_search($matchVal, $keys); // $key = 1;
        $nextindex = $matched + 1;
        $nextValue = $arr[$nextindex];
        ?>
Pavan Sikarwar
  • 833
  • 5
  • 14
1

Try This

$arr = Array
(
    '0900-0930' => 0,
    '0935-1005' => 0,
    '1010-1040' => 0,
    '1045-1115' => 0
);


$matchVal = '0935-1005';

$keys = array_keys($arr);
print $keys[array_search($matchVal,$keys)+1];

Output

1010-1040
shubham715
  • 3,324
  • 1
  • 17
  • 27
1

Please try this.

<?php

$arr = Array
(
    '0900-0930' => 0,
    '0935-1005' => 0,
    '1010-1040' => 0,
    '1045-1115' => 0
);


$matchVal = '0935-1005';

foreach ($arr as $key => $value) {

    if($matchVal == $key){
        echo $key.'<br />';
    }
    next($arr);
    echo key($arr)."<br/>;
}
?>
Mayank Majithia
  • 1,916
  • 16
  • 21