S
S
scclac2022-03-18 20:54:39
PHP
scclac, 2022-03-18 20:54:39

How to get only the first 3 elements from an array?

There is such a device, how to get only 3 first out of it

<?php foreach ($elements as $element): ?>
    
    <?php foreach ($element as $images): ?>
        
        <?php foreach ($images as $image): ?>
        	<?=$image['thumb_src']?>
        <?php endforeach; ?>
        
        
        
    <?php endforeach; ?>
    
<?php endforeach; ?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dsmoke, 2022-03-18
@scclac

foreach (array_slice($images, 0, 3) as $image) {
   $image['thumb_src']
}

https://www.php.net/manual/en/function.array-slice.php

R
ReFeRy, 2022-03-18
@ReFeRy

First, the array you are interested in iterating can be accessed without nested loops, like this: $element[0][0][0]
If you need to output three elements anyway and there are always these three elements, then the easiest way is to print them without iterating:

echo $element[0][0][0]['thumb_src'].$element[0][0][1]['thumb_src'].$element[0][0][2]['thumb_src'];

If with minimal changes it is your code, then like this:
<?php
foreach ($elements as $element)
{
   foreach ($element as $images)
   {
      $i = 1;
      foreach ($images as $image)
      {
         echo $image['thumb_src'];
         if($i++ >= 3)
         {
            break;
         }
      }
   }
}
?>

But there are big questions about what else lies in this array, otherwise your cycles can output something else. Read something on the basic syntax of the language.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question