This article mainly introduces about the PHP source code 21: array_slice function, which has a certain reference value. Now I share it with you. Friends in need can refer to it.
Brief Talk PHP source code twenty-one: array_slice function
array_slice
(PHP 4, PHP 5)
array_slice — Take out a section from the array
Description
array array_slice (array array , int offset [, int length [, bool preserve_keys]] )
array_slice() Returns a sequence in the array array specified by the offset and length parameters.
If offset is non-negative, the sequence will start at this offset in array. If offset is negative, the sequence will start this far from the end in the array.
If length is given and positive, there will be this many cells 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.
This section explains that the implementation in the program is very simple, as follows:
while (pos < offset + length && ...) { ....... }
Note that array_slice() will reset the keys of the array by default. As of PHP 5.0.2, this behavior can be changed by setting preserve_keys to TRUE.
The reset of the keys of the array mentioned here refers to the reset of the numeric keys in the array.
The PHP code is shown below:
<?PHP $arr = array(2 => 2, 1 => 1, 's' => 's', '0' => 'ddd'); var_dump(array_slice($arr, 0)); die(); /* 此段程序会输出:array(4) { [0]=> int(2) [1]=> int(1) ["s"]=> string(1) "s" [2]=> string(3) "ddd" } */
In the source code we can see:
<pre line="1" switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 0, &hpos)) { case HASH_KEY_IS_STRING: // key为字符串,没有重置数组键的操作 zend_hash_update(Z_ARRVAL_P(return_value), string_key, string_key_len, entry, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: // key为数字 if (preserve_keys) { // preserve_keys为true时不重置数字键 zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry, sizeof(zval *), NULL); } else { // 默认情况下重置数字键 zend_hash_next_index_insert(Z_ARRVAL_P(return_value), entry, sizeof(zval *), NULL); } break; }
The above is the entire content of this article. I hope it will be helpful to everyone's study. More related Please pay attention to the PHP Chinese website for content!
Related recommendations:
A brief discussion on PHP source code twenty: About array_flip, array_reverse functions
A brief discussion on PHP source code ten Nine: About array_file, range function
The above is the detailed content of A brief discussion of PHP source code twenty-one: About the array_slice function. For more information, please follow other related articles on the PHP Chinese website!