


[PHP source code reading] array_slice and array_splice functions, slicesplice_PHP tutorial
[PHP source code reading]array_slice and array_splice functions, slicesplice
array_slice and array_splice functions are used to take out a slice of the array, array_splice also replaces the original deleted slice position with a new slice function. Similar to the Array.prototype.splice and Array.prototype.slice methods in javascript.
I have more detailed annotations on the PHP source code on github. If you are interested, you can take a look and give it a star. PHP5.4 source code annotations. You can view the added annotations through the commit record.
array_slice
<p>array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )</p>
Returns the subarray slice of the specified subscript offset and length in the array.
Parameter description
Suppose the length of the first parameter array is num_in.
offset
If offset is a positive number and less than length, the returned array will start from offset; if offset is greater than length, no operation will be performed and it will be returned directly. If offset is a negative number, offset = num_in offset, if num_in offset == 0, offset is set to 0.
length
If length is less than 0, then length will be converted to num_in - offset length; otherwise, if offset length > array_count, then length = num_in - offset. If length is still less than 0 after processing, it will be returned directly.
preserve_keys
The default is false. The original order of numeric key values is not retained by default. If set to true, the original numeric key value order of the array will be retained.
Usage examples
<?<span>php </span><span>$input</span> = <span>array</span>("a", "b", "c", "d", "e"<span>); </span><span>$output</span> = <span>array_slice</span>(<span>$input</span>, 2); <span>//</span><span> returns "c", "d", and "e"</span> <span>$output</span> = <span>array_slice</span>(<span>$input</span>, -2, 1); <span>//</span><span> returns "d"</span> <span>$output</span> = <span>array_slice</span>(<span>$input</span>, 0, 3); <span>//</span><span> returns "a", "b", and "c"</span> <span>print_r</span>(<span>array_slice</span>(<span>$input</span>, 2, -1)); <span>//</span><span> array(0 => 'c', 1 => 'd');</span> <span>print_r</span>(<span>array_slice</span>(<span>$input</span>, 2, -1, <span>true</span>)); <span>//</span><span> array(2 => 'c', 1 => 'd');</span>
Run steps
<p>处理参数:offset、length</p> <p>移动指针到offset指向的位置</p> <p>从offset开始,拷贝length个元素到返回数组</p>
The operation flow chart is as follows
php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input becomes array("red", "green")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input becomes array("red", "yellow")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input becomes array("red", "orange")
$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is array("red", "green",
// "blue", "black", "maroon")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is array("red", "green",
// "blue", "purple", "yellow");
Source code interpretation
In array_splice, there is this piece of code:
<span>/*</span><span> Don't create the array of removed elements if it's not going * to be used; e.g. only removing and/or replacing elements </span><span>*/</span> <span>if</span> (return_value_used) { <span>//</span><span> 如果有用到函数返回值则创建返回数组,否则不创建返回数组</span> <span>int</span> size =<span> length; </span><span>/*</span><span> Clamp the offset.. </span><span>*/</span> <span>if</span> (offset ><span> num_in) { offset </span>=<span> num_in; } </span><span>else</span> <span>if</span> (offset < <span>0</span> && (offset = (num_in + offset)) < <span>0</span><span>) { offset </span>= <span>0</span><span>; } </span><span>/*</span><span> ..and the length </span><span>*/</span> <span>if</span> (length < <span>0</span><span>) { size </span>= num_in - offset +<span> length; } </span><span>else</span> <span>if</span> (((unsigned <span>long</span>) offset + (unsigned <span>long</span>) length) ><span> (unsigned) num_in) { size </span>= num_in -<span> offset; } </span><span>/*</span><span> Initialize return value </span><span>*/</span><span> array_init_size(return_value, size </span>> <span>0</span> ? size : <span>0</span><span>); rem_hash </span>= &<span>Z_ARRVAL_P(return_value); }</span>
The array_splice function returns the deleted slice. The meaning of this code is that if array_splice needs to return a value, then create the return array, otherwise do not create it to avoid wasting space. This is also a little programming trick, return only when needed. For example, if $result = array_splice(...) is used in a function, return_value_used is true.
Summary
This is the end of this article. In daily programming, you should deal with the most special situations first, and then continue, just like you did when implementing these two functions, to avoid making redundant judgments; save new variables if necessary Only apply for new space when the time comes, otherwise it will cause waste.
Original article with limited writing style and limited knowledge. If there is anything wrong in the article, please let me know.
If this article is helpful to you, please click to recommend it, thank you^_^
Finally, I have more detailed annotations on the PHP source code on github. If you are interested, you can take a look and give it a star. PHP5.4 source code annotations. You can view the added annotations through the commit record.
For more source code articles, please visit your personal homepage to continue viewing: hoohack

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



Title: Example of using the Array.Sort function to sort an array in C# Text: In C#, array is a commonly used data structure, and it is often necessary to sort the array. C# provides the Array class, which has the Sort method to conveniently sort arrays. This article will demonstrate how to use the Array.Sort function in C# to sort an array and provide specific code examples. First, we need to understand the basic usage of the Array.Sort function. Array.So

When programming in PHP, we often need to merge arrays. PHP provides the array_merge() function to complete array merging, but when the same key exists in the array, this function will overwrite the original value. In order to solve this problem, PHP also provides an array_merge_recursive() function in the language, which can merge arrays and retain the values of the same keys, making the program design more flexible. array_merge

In PHP, there are many powerful array functions that can make array operations more convenient and faster. When we need to combine two arrays into an associative array, we can use PHP's array_combine function to achieve this operation. This function is actually used to combine the keys of one array as the values of another array into a new associative array. Next, we will explain how to use the array_combine function in PHP to combine two arrays into an associative array. Learn about array_comb

In PHP programming, array is a very important data structure that can handle large amounts of data easily. PHP provides many array-related functions, array_fill() is one of them. This article will introduce in detail the usage of the array_fill() function, as well as some tips in practical applications. 1. Overview of the array_fill() function The function of the array_fill() function is to create an array of a specified length and composed of the same values. Specifically, the syntax of this function is

The array module in Python is a predefined array, so it takes up much less space in memory than a standard list, and can also perform fast element-level operations such as adding, deleting, indexing, and slicing. In addition, all elements in the array are of the same type, so you can use the efficient numerical operation functions provided by the array, such as calculating the average, maximum, and minimum values. In addition, the array module also supports writing and reading array objects directly into binary files, which makes it more efficient when processing large amounts of numerical data. Therefore, if you need to process a large amount of homogeneous data, you may consider using Python's array module to optimize the execution efficiency of your code. To use the array module, you first need to

In Java programming, array is an important data structure. Arrays can store multiple values in a single variable, and more importantly each value can be accessed using an index. But while working with arrays, some exceptions may occur, one of them is ArrayStoreException. This article will discuss common causes of ArrayStoreException exceptions. 1. Type mismatch The element type must be specified when the array is created. When we try to store incompatible data types into an array, it throws

In PHP programming, array is a frequently used data type. There are also quite a few array operation functions, including the array_change_key_case() function. This function can convert the case of key names in the array to facilitate our data processing. This article will introduce how to use the array_change_key_case() function in PHP. 1. Function syntax and parameters array_change_ke

Java is a very powerful programming language that is widely used in various development fields. However, during Java programming, developers often encounter ArrayIndexOutOfBoundsException exceptions. So, what are the common causes of this anomaly? ArrayIndexOutOfBoundsException is a common runtime exception in Java. It means that when accessing data, the array subscript exceeds the range of the array. Common reasons include
