how to skip elements in foreach loop

后端 未结 7 1812
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 17:56

I want to skip some records in a foreach loop.

For example, there are 68 records in the loop. How can I skip 20 records and start from record #21?

7条回答
  •  萌比男神i
    2020-12-05 18:32

    if want to skipped some index then make an array with skipped index and check by in_array function inside the foreach loop if match then it will be skip.

    Example:

    //you have an array like that
    $data = array(
        '1' => 'Hello world',
        '2' => 'Hello world2',
        '3' => 'Hello world3',
        '4' => 'Hello world4',
        '5' => 'Hello world5',// you want to skip this
        '6' => 'Hello world6',// you want to skip this
        '7' => 'Hello world7',
        '8' => 'Hello world8',
        '9' => 'Hello world8',
        '10' => 'Hello world8',//you want to skip this
    );
    
    //Ok Now wi make an array which contain the index wich have to skipped
    
    $skipped = array('5', '6', '10');
    
    foreach($data as $key => $value){
        if(in_array($key, $skipped)){
            continue;
        }
        //do your stuf
    }
    

提交回复
热议问题