phparraysslice

Isolate the first n number of elements in an array


Here is the code in question:

$countries = array("New Zealand", "Australia", "United Kingdom", "New Zealand");

I am after some code that will let me declare a new array from this previous array with me specifying how many items in the array.

eg:

If I did something like this:

$newArray = $countries[1], $newArray will hold "New Zealand" and "Australia"
$newArray = $countries[2], $newArray will hold "New Zealand", "Australia" and "United Kingdom"

Currently I am doing this by using a for loop. Is there an easier/more efficient way to do this?


Solution

  • Use array_slice()

    $array1 = array_slice($input, 0, 2);
    $array2 = array_slice($input, 0, 3);