title: How to access the nth item in a Laravel collection?
body: <p>I guess I am breaking all the rules by deliberately making a duplicate question...</p>
  
  <p>The <a href="https://stackoverflow.com/questions/24443949/how-to-access-the-nth-object-in-a-laravel-collection-object">other question</a> has an accepted answer. It obviously solved the askers problem, but it did not answer the title question.</p>
  
  <p>Let's start from the beginning - the <code>first()</code> method is implemented approximately like this:</p>
  
  <pre><code>foreach ($collection as $item)
      return $item;
  </code></pre>
  
  <p>It is obviously more robust than taking <code>$collection[0]</code> or using other suggested methods. </p>
  
  <p>There might be no item with index <code>0</code> or index <code>15</code> even if there are 20 items in the collection. To illustrate the problem, let's take this collection out of the docs:</p>
  
  <pre><code>$collection = collect([
      ['product_id' =&gt; 'prod-100', 'name' =&gt; 'desk'],
      ['product_id' =&gt; 'prod-200', 'name' =&gt; 'chair'],
  ]);
  
  $keyed = $collection-&gt;keyBy('product_id');
  </code></pre>
  
  <p>Now, do we have any reliable (and preferably concise) way to access nth item of <code>$keyed</code>?</p>
  
  <p>My own suggestion would be to do:</p>
  
  <pre><code>$nth = $keyed-&gt;take($n)-&gt;last();
  </code></pre>
  
  <p>But this will give the wrong item (<code>$keyed-&gt;last()</code>) whenever <code>$n &gt; $keyed-&gt;count()</code>. How can we get the nth item if it exists and <code>null</code> if it doesn't just like <code>first()</code> behaves?</p>
  
  <h2>Edit</h2>
  
  <p>To clarify, let's consider this collection:</p>
  
  <pre><code>$col = collect([
      2 =&gt; 'a',
      5 =&gt; 'b',
      6 =&gt; 'c',
      7 =&gt; 'd']);
  </code></pre>
  
  <p>First item is <code>$col-&gt;first()</code>. How to get the second?</p>
  
  <p><code>$col-&gt;nth(3)</code> should return <code>'c'</code> (or <code>'c'</code> if 0-based, but that would be inconsistent with <code>first()</code>). <code>$col[3]</code> wouldn't work, it would just return an error.</p>
  
  <p><code>$col-&gt;nth(7)</code> should return <code>null</code> because there is no seventh item, there are only four of them. <code>$col[7]</code> wouldn't work, it would just return <code>'d'</code>.</p>
  
  <p>You could rephrase the question as "How to get nth item in the foreach order?" if it's more clear for some.</p>