


PHP array interception, equal division and replacement of part of the array
In this article, we will introduce the interception of the array (array_slice) and equal division (array_chunk) and replacement (array_splice) and the difference between array_slice and array_splice!
In the previous three articles "How to sort PHP array?" "PHP array random order and reverse order" and "PHP array In "Reverse Order Arrangement", we introduced the sorting of arrays, including ascending order, descending order, disordered order and reverse order of arrays. I believe everyone has a certain understanding of the sorting of arrays. Today we will introduce another group Array functions!
What is an intercepted array? (array_slice)
array_slice takes out a segment of elements from the array. The first parameter is the original array, and the second parameter is the original array. The first parameter is the starting subscript (remember that the array starts from 0), and the third parameter is the number of elements taken from the subscript. If not set, it will be taken until the end of the array by default!
array_slice syntax format is as follows:
array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
Parameter | Description |
array | Input array. |
offset | If offset is non-negative, the sequence will start at this offset in array. If offset is negative, the sequence will start this far away from the end in the array. |
length | If length is given and positive, there will be this many units in the sequence. If length is given and negative, the sequence will terminate this far from the end of the array. If omitted, the sequence will start at offset and go to the end of array. |
preserve_keys | Note that array_slice() will reorder and reset the numeric index of the array by default. You can change this behavior by setting preserve_keys to TRUE. |
具体我们看下面的实例代码:
<?php header("Content-Type:text/html; charset=utf-8"); $arr=array("PHP中文网", "www.php.cn", "百度","搜狗"); $array = array_slice($arr,1,2); //从下标1开始截取,取2个元素,赋给新的变量 print_r($array); ?>
输出的结果为:
上面的实例示我们指定截取多少个元素的,如果我们不指定呢?也就是array_slice()的第三个参数不写会是什么情况?下面我们一起看下示例代码,还是以上面代码为例:
<?php header("Content-Type:text/html; charset=utf-8"); $arr=array("PHP中文网", "www.php.cn", "百度","搜狗"); $array = array_slice($arr,1); //从下标1开始截取,截取到最后一个元素,赋给新的变量 print_r($array); ?>
输出的结果为:
看到这大家应该就明白了,当array_slice()的第三个参数不写,那么就会默认截取到数组的最后一个元素!array_slice()函数的第二参数就是指定从哪个下标开始截取!
这里要说明一下:
array_slice仅仅是将数组中的一段取出重新赋值给别的数组,而原数组是不受影响的,也就是说,上面代码数组中的 www.php.cn和百度依然存在的!
什么是替换部分数组?(array_splice)
array_splice() 函数与 array_slice() 函数类似,选择数组中的一系列元素,但不返回,而是删除它们并用其它值代替,换句话说就是去掉数组中的某一部分并用其它值取代。
array_splice语法格式如下:
array array_splice ( array &$input , int $offset [, int $length = count($input) [, mixed $replacement = array() ]] )
把 input 数组中由 offset 和 length 指定的单元去掉,如果提供了 replacement参数,则用其中的单元取代。
注意:
1.如果 replacement 不是数组,会被 类型转换 成数组 (例如: (array) $replacement)。 当传入的 replacement 是个对象或者 NULL,会导致未知的行为出现。
2.注意 input 中的数字键名不被保留。
下面我们来看具体的示例代码:
<?php header("Content-Type:text/html; charset=utf-8"); $arr=array("PHP", "语言", "百度","搜狗"); print_r($arr); echo "<br>"; array_splice($arr,1,2,array("PHP中文网","www.php.cn","php.cn")); print_r($arr); ?>
输出的结果为:
从上面的实例中可以看出 数组的“语言”,“百度”被“PHP中文网”,“www.php.cn”,"php.cn"替代换区。
上面的示例中,我们是将替换后将其赋给一个新的数组,那么如果没有新的数组呢?我们看下面的实例:
<?php header("Content-Type:text/html; charset=utf-8"); $arr=array("PHP", "语言", "百度","搜狗"); print_r($arr); echo "<br>"; array_splice($arr,1,2); print_r($arr); ?>
输出的结果为:
从输出的结果中就可以看出,如果没有新的数组,那么就相当于 array_slice,切掉相关位置的数组!
array_splice和array_slice两个函数的相同点和不同点
相同点:
可以实现对数组,进行指定下标位置,和指定元素个数进行数组切割
(其实,就是删除指定的数组元素)
不同点:
array_slice 是传值函数, 原数组不会变化,切割后,可以赋给一个新数组!
array_splice是传址函数,会直接修改原数组,可以设置新的元素,去替换被切割掉的数组元素!
什么是等分数组?(array_chunk)
array_chunk()函数是将数组中的元素数量等分的切割成一个二维数组,其中每个数组的单元数目由第二个参数 size 决定。数组的最后一个单元数目可能会少于 size 个,下面我们一起看下语法格式:
下面我们直接用实例代码带大家了解:
<?php header("Content-Type:text/html; charset=utf-8"); $input_array = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; $new_array = array_chunk($input_array, 3); print_r($new_array); ?>
输出结果为:
在下一篇文章中我们将介绍合并数组的函数,具体详情阅读《PHP数组如何合并?》
【相关教程推荐】
1. Relevant topic recommendations: "php array (Array)"
The above is the detailed content of Interception, equal division and replacement of partial arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool