Home >Backend Development >PHP Tutorial >How to Extract the First N Elements from a PHP Array?

How to Extract the First N Elements from a PHP Array?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 15:37:02646browse

How to Extract the First N Elements from a PHP Array?

How to Get the First N Elements of an Array

This question has already been addressed in a previous discussion. Here's the best solution:

Use array_slice()

The PHP manual provides an example:

<code class="php">$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"</code>

Caution:

array_slice() resets and reorders the numeric array indices. To preserve the original indices, set the preserve_keys flag to true (4th parameter, available since PHP 5.0.2):

<code class="php">$output = array_slice($input, 2, 3, true);</code>

This will produce the following output, preserving the original indices:

<code class="php">array([3]=>'c', [4]=>'d', [5]=>'e');</code>

The above is the detailed content of How to Extract the First N Elements from a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn