Home Backend Development PHP Tutorial PHP array_splice函数使用方法

PHP array_splice函数使用方法

Mar 30, 2017 pm 04:11 PM

本文介绍了phparray_slicearray_splice函数解析,php拆分数组的二个函数(array_slice()、array_splice()),各举一个例子,供大家学习参考。

array_slice和array_splice函数是用在取出数组的一段切片,array_splice还有用新的切片替换原删除切片位置的功能。类似javascript中的Array.prototype.splice和Array.prototype.slice方法。

array_slice

array array_slice ( array $array , 
int $offset [, 
int $length = NULL [, bool $preserve_keys = false ]] )
Copy after login

返回数组中指定下标offset和长度length的子数组切片。

参数说明
设第一个参数数组的长度为num_in。

offset

如果offset是正数且小于length,则返回数组会从offset开始;如果offset大于length,则不操作,直接返回。如果offset是负数,则offset = num_in+offset,如果num_in+offset == 0,则将offset设为0。

length

如果length小于0,那么会将length转为num_in - offset + length;否则,如果offset+length > array_count,则length = num_in - offset。如果处理后length还是小于0,则直接返回。

preserve_keys

默认是false,默认不保留数字键值原顺序,设为true的话会保留数组原来的数字键值顺序。

使用实例

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);   // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3);  // returns "a", "b", and "c"

print_r(array_slice($input, 2, -1)); // array(0 => &#39;c&#39;, 1 => &#39;d&#39;);
print_r(array_slice($input, 2, -1, true)); // array(2 => &#39;c&#39;, 1 => &#39;d&#39;);
Copy after login

运行步骤

  • 处理参数:offset、length

  • 移动指针到offset指向的位置

  • 从offset开始,拷贝length个元素到返回数组

运行流程图如下

array_splice


array array_splice ( array &$input , int $offset [, 
int $length = 0 [, mixed $replacement = array() ]] )
Copy after login

删除input中从offset开始length个元素,如果有replacement参数的话用replacement数组替换删除掉的元素。

参数说明

array_splice函数中的offset和length参数跟array_slice函数中的用法一样。

replacement

  • 如果这个参数设置了,那么函数将使用replacement数组来替换。

  • 如果offset和length指定了没有任何元素需要移除,那么replacement会被插入到offset的位置。

  • 如果replacement只有一个元素,可以不用array()去包着它。

使用示例

<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input变为 array("red", "green")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input变为 array("red", "yellow")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input变为 array("red", "orange")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input为 array("red", "green",
//     "blue", "black", "maroon")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input为 array("red", "green",
//     "blue", "purple", "yellow");
Copy after login

源码解读

在array_splice中,有这么一段代码:

 /* Don&#39;t create the array of removed elements if it&#39;s not going
   * to be used; e.g. only removing and/or replacing elements */
  if (return_value_used) { // 如果有用到函数返回值则创建返回数组,否则不创建返回数组
    int size = length;

    /* Clamp the offset.. */
    if (offset > num_in) {
      offset = num_in;
    } else if (offset < 0 && (offset = (num_in + offset)) < 0) {
      offset = 0;
    }

    /* ..and the length */
    if (length < 0) {
      size = num_in - offset + length;
    } else if (((unsigned long) offset + (unsigned long) length) > (unsigned) num_in)     {
      size = num_in - offset;
    }

    /* Initialize return value */
    array_init_size(return_value, size > 0 ? size : 0);
    rem_hash = &Z_ARRVAL_P(return_value);
  }
Copy after login

array_splice函数返回的是被删除的切片。这段代码的意思是,如果array_splice需要返回值,那么才创建返回数组,否则不创建,以免浪费空间。这也是一个编程小技巧,仅当需要的时候才返回。比如在函数中使用$result = array_splice(...),那么return_value_used就是true。

总结

到此本文结束,在平时编程中,应当像这两个函数实现时的做法一样,将最特殊的情况先处理掉,然后再继续,以免做了多余的判断;有需要保存新变量的时候才申请新的空间,不然会造成浪费。

 以上就是PHP array_splice函数使用方法的内容,更多相关内容请关注PHP中文网(www.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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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.

See all articles