Home » Php » php – How do I pick only the first few items in an array?

php – How do I pick only the first few items in an array?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Here’s something simple for someone to answer for me. I’ve tried searching but I don’t know what I’m looking for really.

I have an array from a JSON string, in PHP, of cast and crew members for a movie.

Here I am pulling out only the people with the job name ‘Actor’

  foreach ($movies[0]->cast as $cast) {
      if ($cast->job == 'Actor') {
    echo '<p><a href="people.php?id=' . $cast->id . '">' . $cast->name . ' - ' . $cast->character . '</a></p>';
      }
  }

The problem is, I would like to be able to limit how many people with the job name ‘Actor’ are pulled out. Say, the first 3.

So how would I pick only the first 3 of these people from this array?

How to&Answers:

Use a variable called $num_actors to track how many you’ve already counted, and break out of the loop once you get to 3.

$num_actors = 0;
foreach ( $movies[0]->cast as $cast ) {
    if ( $cast->job == 'Actor' ) {
        echo '...';

        $num_actors += 1;
        if ( $num_actors == 3 )
            break;
    }
}

Answer:

OK – this is a bit of over-kill for this problem, but perhaps it serves some educational purposes. PHP comes with a set of iterators that may be used to abstract iteration over a given set of items.

class ActorIterator extends FilterIterator {
    public function accept() {
        return $this->current()->job == 'Actor';
    }
}

$maxCount = 3;
$actors   = new LimitIterator(
    new ActorIterator(
        new ArrayIterator($movies[0]->cast)
    ), 
    0, 
    $maxCount
);
foreach ($actors as $actor) {
    echo /*... */;
}

By extending the abstract class FilterIterator we are able to define a filter that returns only the actors from the given list. LimitIterator allows you to limit the iteration to a given set and the ArrayIterator is a simple helper to make native arrays compatible with the Iterator interface. Iterators allow the developer to build chains that define the iteration process which makes them extremely flexible and powerful.

As I said in the introduction: the given problem can be solved easily without this Iterator stuff, but it provides the developer with some extended options and enables code-reuse. You could, for example, enhance the ActorIterator to some CastIterator that allows you to pass the cast type to filter for in the constructor.

Answer:

$actors=array_filter($movies[0]->cast, function ($v) {
    return $v->job == 'Actor';
});

$first3=array_slice($actors, 0, 3);

or even

$limit=3;
$actors=array_filter($movies[0]->cast, function ($v) use (&$limit) {
    if ($limit>0 && $v->job == 'Actor') {
         $limit--;
         return true;
    }
    return false;
});

Answer:

Add a counter and an if statement.

$count = 0;
foreach ($movies[0]->cast as $cast)
{
  if ($cast->job == 'Actor')
  {
    echo '<p><a href="people.php?id=' . $cast->id . '">' . $cast->name . ' - ' . $cast-character . '</a></p>';

    if($count++ >= 3)
      break;
  }
}

Answer:

$limit = 3;
$count = 0;

  foreach ($movies[0]->cast as $cast) {
      // You can move the code up here if all you're getting is Actors
      if ($cast->job == 'Actor') {
          if ($count == $limit) break;// stop the loop
          if ($count == $limit) continue;// OR move to next item in loop
          $count++;
          echo '<p><a href="people.php?id=' 
                  . $cast->id 
                  . '">' 
                  . $cast->name 
                  . ' - ' 
                  . $cast->character 
                  . '</a></p>';
      }
  }