php how to loop through array until condition is met?

10,708

Solution 1

you could do something like:

$imgs = array(); $imgs_count = 0;
foreach ( $p as $img ) {
    if ( !empty($img) ) {
        $imgs[] = $img;
        $imgs_count++;
    }
    if ( $imgs_count === 10 ) break;
}

Solution 2

You can simply call array_filter() to get only the non-empty elements from the array. array_filter() can take a callback function to determine what to remove, but in this case empty() will evaluate as FALSE and no callback is needed. Any value that evaluates empty() == TRUE will simply be removed.

$p=array($img1, $img2.....$img20);
$nonempty = array_filter($p);

// $nonempty contains only the non-empty elements.

// Now dow something with the non-empty array:
foreach ($nonempty as $value) {
   something();
}

// Or use the first 10 values of $nonempty
// I don't like this solution much....
$i = 0;
foreach ($nonempty as $key=>$value) {
  // do something with $nonempty[$key];
  $i++;
  if ($i >= 10) break;
}

// OR, it could be done with array_values() to make sequential array keys:
// This is a little nicer...
$nonempty = array_values($nonempty);
for ($i = 0; $i<10; $i++) {
   // Bail out if we already read to the end...
   if (!isset($nonempty[$i]) break;

   // do something with $nonempty[$i]
}

Solution 3

Have you thought about limiting your results in the sql query?

select * from image where img != '' limit 10

This way you are always given up to 10 results that are not empty.

Solution 4

$new_array[] = $p[$i];

Will store $p[$i] into the next element of $new_array (a.k.a array_push()).

Share:
10,708
huzzah
Author by

huzzah

Updated on July 02, 2022

Comments

  • huzzah
    huzzah almost 2 years

    I have a database table with images that I need to display. In my view, I'd like to display UP TO 10 images for each result called up. I have set up an array with the 20 images that are available as a maximum for each result (some results will only have a few images, or even none at all). So I need a loop that tests to see if the array value is empty and if it is, to move onto the next value, until it gets 10 results, or it gets to the end of the array.

    What I'm thinking I need to do is build myself a 2nd array out of the results of the test, and then use that array to execute a regular loop to display my images. Something like

    <?php 
      $p=array($img1, $img2.....$img20);
    
      for($i=0; $i<= count($p); $i++) {
        if(!empty($i[$p])) {
        ...code
        }
      }
    ?>
    

    How do I tell it to store the array values that aren't empty into a new array?

    • Madara's Ghost
      Madara's Ghost over 12 years
      I think you mean $p[$i] and not $i[$p].
    • Tom
      Tom over 12 years
      Do you want to output 10 images, or do you want to split the array into multiple arrays with 10 images in each array? Or what exactly is it you would like to do?
    • huzzah
      huzzah over 12 years
      Just 10, no multiple arrays. Working on a solution below.
  • huzzah
    huzzah over 12 years
    Thank you! Unfortunately, for some reason, it is still holding empty values, because using a for loop gives me "undefined offset" in the last values of the array when there are less than 10 images in the first part of the array (the $p array has results from two tables). You can view the output here: rentcondos4less.cloudmedia.biz/lodgings/debug
  • Michael Berkowski
    Michael Berkowski over 12 years
    @HeatherWalters I just made a change above. Forgot that if you deleted elements from the array, the corresponding keys wouldn't necessarily be sequential anymore.
  • huzzah
    huzzah over 12 years
    This is actually working for me, except that about half the time, I'm getting this awful 'base table or view not found....tables cloudmed.images does not exist' instead of my little debug page (I'm using Cakephp by the way). And worse, if I keep trying to reload the page, Google chrome blocks me from accessing the page: Error 139 (net::ERR_TEMPORARILY_THROTTLED): Requests to the server have been temporarily throttled. What the heck am I doing wrong?!!!
  • huzzah
    huzzah over 12 years
    See my comment above to @felipelavinz, on top of it all, I am getting this weird server request throttled message half the time when I implement your code (as well as his....my hosting company sucks? Did my function cause the lights to dim in LA?)
  • huzzah
    huzzah over 12 years
    I think my server is pooping out on me, otherwise, this works great. Thank you!
  • huzzah
    huzzah over 12 years
    No, it's still happening today. Anyone have a clue what is going on in this function that might cause that?
  • felipelavinz
    felipelavinz over 12 years
    That's actually a built-in Chrome prevetion for DDOS... check google.com/support/forum/p/Chrome/…
  • huzzah
    huzzah over 12 years
    Yeah, I'm ok with the Chrome message. It is DEFINITELY this function that is causing the error about half the time I load this page. It happens no where else in my app. If anyone has any idea about why my server craps out on me because of this, I'm open to changing things around.