Home > Backend Development > PHP Problem > Correct use of array_slice() function in PHP

Correct use of array_slice() function in PHP

autoload
Release: 2023-03-09 12:32:01
Original
2012 people have browsed it

Array is a common data type in PHP. The data in the array is usually taken out directly through the key of the array, or obtained through loop traversal. How to take out a section in the array, this article will show you how to use array_slice()The function takes out a segment from the array. First, let’s take a look at the syntax:

array_slice ( array $array   , int $offset   , int $length = null   , bool $preserve_keys = false   ) : array
Copy after login
  • $array: the input array.

  • $offset: Specifies the starting position of the element to be retrieved

  • $length: Optional, specifies the length of the returned array.

  • $preserve_keys: Optional, specifies whether the function retains the key name or resets the key name

  • Return value: Returns one of the segments. If the $offset parameter is larger than the $array size, an empty $array will be returned.

Code example:

1. There are two parameters

<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1));
?>
Copy after login
输出:Array
( [0] => green[1] => blue[2] => yellow[3] => brown)
Copy after login

2. Three parameters

<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,3));
?>
Copy after login
输出:Array
( [0] => green[1] => blue[2] => yellow)
Copy after login

3. Four parameters

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"brown");
print_r(array_slice($a,1,2));

$a=array("0"=>"red","1"=>"green","2"=>"blue","3"=>"yellow","4"=>"brown");
print_r(array_slice($a,1,2));
?>
Copy after login
输出:Array([b] => green [c] => blue)
Array([0] => green[1] => blue)
Copy after login

Recommended: 2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of Correct use of array_slice() function in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template