[PHP源码阅读]array_slice和array_splice函数,slicesplice

  • array
  • 2022-06-11 18:36:59

[PHP源码阅读]array_slice和array_splice函数,slicesplice

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

我在github上有对PHP源码更详细的注解。感兴趣的可以围观一下,给个star。PHP5.4源码注解。可以通过commit记录查看已添加的注解。

array_slice

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

返回数组中指定下标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 => 'c', 1 => 'd');
print_r(array_slice($input, 2, -1, true)); // array(2 => 'c', 1 => 'd');

运行步骤

处理参数:offset、length

移动指针到offset指向的位置

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

运行流程图如下

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

源码解读

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

    /* Don't create the array of removed elements if it'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

猜你喜欢