What is array_slice ()?

Update

I'm new to PHP development: I looked at the PHP website for the - function array_slice. I read and looked at an example, but I do not understand this. Can someone explain this in clear words for me?

I think this works as follows:

$example = array(1,2,3,4,5,6,7,8,9);
$offset = 2;
$length = 5;
$newArray = array_slice($example, offset, length);

the result of $newArray is: $newArray(3,4,5,6,7);
+3
source share
5 answers

In addition to stefgosselin's answer , which has some errors: Let's start with its array:

$input = array(1,2,3);

It contains:

array(3) {
    [0]=> int(1)
    [1]=> int(2)
    [2]=> int(3)
}

Then you do array_slice:

var_dump(array_slice($input, 1));

The function will return values ​​after the first element (this is what the second argument is, a means of bias). But notice the keys!

array(2) {
    [0]=> int(2)
    [1]=> int(3)
}

, , true preserve_keys. , length, NULL, , .

var_dump(array_slice($input, 1, NULL, true));

, stefgosselin () .

array(2) {
    [1]=> int(2)
    [2]=> int(3)
}
+4

. man, , 0, ..

 $array_slice = $array(1,2,3);

:

$array[0] = 1,
$array[1] = 2,
$array[2] = 3

, array_slice(1) of $array_sliced :

$arraysliced = array_slice($array_slice, 1);
$arraysliced[1] = 2;
$arraysliced[2] = 3; 
+2

, , .

:

$output = array();
for ($i = 0; $i++; $i < count($input)) {
  if ($i < $start)
    continue;
  if ($i > $start + $length)
    break;
  $output[] = $input[$i];
}
+1

. , . .

0

PHP array_slice(), . , , ( ), . , , ( ). :

$authors = array( "Steinbeck",
"Kafka", "Tolkien", "Dickens" );
$authorsSlice = array_slice(
$authors, 1, 2 ); // Displays "Array
( [0] = > Kafka [1] = > Tolkien )"
print_r( $authorsSlice );

, array_slice(), :

$authors = array( "Steinbeck", "Kafka", "Tolkien", "Dickens" );
$authorsSlice = array_slice( $authors, 1 );
// Displays "Array ( [0] = > Kafka [1] = > Tolkien [2] = > Dickens )";
print_r( $authorsSlice );

, array_slice() , . , , true, array_slice():

$authors = array( "Steinbeck", "Kafka", "Tolkien", "Dickens" );
// Displays "Array ( [0] = > Tolkien [1] = > Dickens )";
print_r( array_slice( $authors, 2, 2 ) );
// Displays "Array ( [2] = > Tolkien [3] = > Dickens )";
print_r( array_slice( $authors, 2, 2, true ) );
0

All Articles