How to stop a loop PHP

后端 未结 4 681
没有蜡笔的小新
没有蜡笔的小新 2021-01-29 06:10

I\'m trying to figure out if its possible to stop a foreach loop in PHP, like this,

$arr = array(\'Joe\', \'Jude\', \'James\', \'Pitch\', \'Tim\');
$i=0;
foreach         


        
相关标签:
4条回答
  • 2021-01-29 06:47

    You can break out of a loop with break.

    0 讨论(0)
  • 2021-01-29 06:55

    1)As said earlier u need to increment the loop. 2)...if ur using multiple "foreach" that are nested,you can do break 'n' to get out of n nested loop,where n will specify any number from 1 to the total number of loops that you have used.Hope it helps!

    0 讨论(0)
  • 2021-01-29 06:56

    Use break and increment $i.

    $arr = array('Joe', 'Jude', 'James', 'Pitch', 'Tim');
    $i=0;
    foreach($arr as $val){
        echo $val;
        if(++$i == 2){
           break; 
       }
    }
    
    0 讨论(0)
  • 2021-01-29 07:14

    You can use good old keyword break here as well. Followed by a semicolon ; of course.

    if($i == 2){
         break;
    }
    

    Manual for break

    0 讨论(0)
提交回复
热议问题