


[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

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


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

Dreamweaver Mac version
Visual web development tools

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version
Useful JavaScript development tools