search
HomeBackend DevelopmentPHP Tutorialphp function array_slice() that returns a selected part of an array

Example

Start taking out the second element of the array and return all elements until the end of the array:

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

Definition and usage

array_slice() function return Selected portion of the array.

Note: If the array has string keys, the returned array will retain the keys (see Example 4).

Syntax

array_slice(array,start,length,preserve)
Parameters Description
array Required. Specifies an array.
start Required. numerical value. Specifies the starting position of the element to be retrieved. 0 = first element. If the value is set to a positive number, it will be taken from front to back. If the value is set to a negative number, the absolute value of start is taken from back to front. -2 means start from the second to last element of the array.
length Optional. numerical value. Specifies the length of the returned array. If the value is set to an integer, that number of elements is returned. If this value is set to a negative number, the function will terminate fetching this far from the end of the example array. If this value is not set, all elements starting from the position set by the start parameter to the end of the array are returned.
preserve Optional. Specifies whether the function retains key names or resets key names. Possible values:
  • true - keep key names

  • false - default. Reset key name

Technical details

The preserve parameter is new in PHP 5.0.2.

更多实例

实例 1

从数组的第一个元素开始取出,并返回两个元素:

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

实例 2

使用负的 start 参数:

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

实例 3

带有设置为 true 的 preserve 参数:

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

实例 4

带有字符串和整数键名:

<?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));
?>

array_slice函数实现的分页方法非常好用,分享如下:

<?php 
//假定一个结果集二维数组: 
   $arr = array(array(&#39;name&#39;=> &#39;name1&#39;,&#39;sex&#39; => &#39;sex1&#39;,&#39;job&#39; => &#39;job1&#39;), 
              array(&#39;name&#39;=> &#39;name2&#39;,&#39;sex&#39; => &#39;sex2&#39;,&#39;job&#39; => &#39;job2&#39;), 
              array(&#39;name&#39;=> &#39;name3&#39;,&#39;sex&#39; => &#39;sex3&#39;,&#39;job&#39; => &#39;job3&#39;), 
              array(&#39;name&#39;=> &#39;name4&#39;,&#39;sex&#39; => &#39;sex4&#39;,&#39;job&#39; => &#39;job4&#39;), 
              array(&#39;name&#39;=> &#39;name5&#39;,&#39;sex&#39; => &#39;sex5&#39;,&#39;job&#39; => &#39;job5&#39;), 
              array(&#39;name&#39;=> &#39;name6&#39;,&#39;sex&#39; => &#39;sex6&#39;,&#39;job&#39; => &#39;job6&#39;), 
              array(&#39;name&#39;=> &#39;name7&#39;,&#39;sex&#39; => &#39;sex7&#39;,&#39;job&#39; => &#39;job7&#39;), 
              array(&#39;name&#39;=> &#39;name8&#39;,&#39;sex&#39; => &#39;sex8&#39;,&#39;job&#39; => &#39;job8&#39;), 
              array(&#39;name&#39;=> &#39;name9&#39;,&#39;sex&#39; => &#39;sex9&#39;,&#39;job&#39; => &#39;job9&#39;), 
              array(&#39;name&#39;=> &#39;name10&#39;,&#39;sex&#39; => &#39;sex10&#39;,&#39;job&#39; => &#39;job10&#39;), 
              array(&#39;name&#39;=> &#39;name11&#39;,&#39;sex&#39; => &#39;sex11&#39;,&#39;job&#39; => &#39;job11&#39;), 
              array(&#39;name&#39;=> &#39;name12&#39;,&#39;sex&#39; => &#39;sex12&#39;,&#39;job&#39; => &#39;job12&#39;), 
     ); 
 
 //计算总记录条数 
 $num = count($arr); 
 //规定每页显示的条数 
 $perpage = 3; 
 //计算页数 
 $pages = ceil($num/$perpage); 
 //echo $num,$perpage,$pagecount;exit; 
 if(is_numeric($_REQUEST[&#39;page&#39;])) 
 { 
  if($_REQUEST[&#39;page&#39;]<1){ 
   $page = 1; 
  }elseif($_REQUEST[&#39;page&#39;]>$pages) 
  { 
   $page = $pages; 
  }else{ 
  $page = $_REQUEST[&#39;page&#39;]; 
   } 
 }else{ 
  $page = 1; 
 } 
 $start = ($page-1)*$perpage; 
 $newpage = array_slice($arr,$start,$perpage,true); 
 //print_r($newpage);exit; 
?> 
<table cellpadding="0" cellspacing="0" border="1"> 
 <tr> 
  <td>name</td> 
  <td>sex</td> 
  <td>job</td> 
 </tr> 
<?php 
 foreach($newpage as $k => $v) 
{ 
?> 
 <tr> 
  <td><?php echo  $v[&#39;name&#39;]; ?></td> 
  <td><?php echo  $v[&#39;sex&#39;]; ?></td> 
  <td><?php echo  $v[&#39;job&#39;]; ?></td> 
 </tr> 
<?php 
} 
?> 
</table> 
<?php 
if($page>1){ 
 echo "<a href=&#39;?page=1&#39;>首页</a>"; 
 echo "<a href=&#39;?page=".($page-1)."&#39;>上一页</a>"; 
}
if($page<$pages) 
{ 
 echo "<a href=&#39;?page=".($page+1)."&#39;>下一页</a>"; 
 echo "<a href=&#39;?page=".$pages."&#39;>末页</a>"; 
} 
?>


Return value: Return the selected portion of the array.
PHP Version: 4+
##Update Log :

The above is the detailed content of php function array_slice() that returns a selected part of an 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
What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

What is the importance of setting the httponly flag for session cookies?What is the importance of setting the httponly flag for session cookies?May 03, 2025 am 12:10 AM

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

What problem do PHP sessions solve in web development?What problem do PHP sessions solve in web development?May 03, 2025 am 12:02 AM

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft