Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save monecchi/00217ab4aa60adcd7165f61adb5faa5f to your computer and use it in GitHub Desktop.
Save monecchi/00217ab4aa60adcd7165f61adb5faa5f to your computer and use it in GitHub Desktop.
Array easily exit the foreach loop after x number of iterations
// Credit goes to authors of answers here: http://stackoverflow.com/a/2865393/1152876
<?php
/*
* Example array, the values are grabbed from a custom field on WordPress.
* Works well if you need a solution that can accept any array.
*/
$array = get_post_meta( get_the_ID(), '_prefix_my_custom_field', true );
$i=0;
foreach($array as $arr){
// whatever you want to do here
$i++;
if($i==3) break;
}
?>
<?php
/*
* Optimized version with a for loop. it's more bug-proof (the control variables are all inside the for statement),
* and just reading it you know how many times it will be executed. break; or continue; should be avoided if possible.
* Does not play well with arrays that doesn't have contiguous numeric indexes starting at 0. var_dump($array) and check it first.
*/
for($i=0;$i<3;$i++){
$array = $arr[i];
// whatever you want to do here
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment