Skip to content

Commit c6bc209

Browse files
committed
Simplify array_unshift()
1 parent f9a70c5 commit c6bc209

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

ext/standard/array.c

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2207,21 +2207,34 @@ PHP_FUNCTION(array_unshift)
22072207
{
22082208
zval *args, /* Function arguments array */
22092209
*stack; /* Input stack */
2210-
HashTable *new_hash; /* New hashtable for the stack */
2211-
HashTable old_hash;
2210+
HashTable new_hash; /* New hashtable for the stack */
22122211
int argc; /* Number of function arguments */
2212+
int i;
2213+
zend_string *key;
2214+
zval *value;
22132215

22142216
if (zend_parse_parameters(ZEND_NUM_ARGS(), "a/+", &stack, &args, &argc) == FAILURE) {
22152217
return;
22162218
}
22172219

2218-
/* Use splice to insert the elements at the beginning. Destroy old
2219-
* hashtable and replace it with new one */
2220-
new_hash = php_splice(Z_ARRVAL_P(stack), 0, 0, &args[0], argc, NULL);
2221-
old_hash = *Z_ARRVAL_P(stack);
2222-
*Z_ARRVAL_P(stack) = *new_hash;
2223-
FREE_HASHTABLE(new_hash);
2224-
zend_hash_destroy(&old_hash);
2220+
zend_hash_init(&new_hash, zend_hash_num_elements(Z_ARRVAL_P(stack)) + argc, NULL, ZVAL_PTR_DTOR, 0);
2221+
for (i = 0; i < argc; i++) {
2222+
if (Z_REFCOUNTED(args[i])) {
2223+
Z_ADDREF(args[i]);
2224+
}
2225+
zend_hash_next_index_insert_new(&new_hash, &args[i]);
2226+
}
2227+
ZEND_HASH_FOREACH_STR_KEY_VAL_IND(Z_ARRVAL_P(stack), key, value) {
2228+
if (key) {
2229+
zend_hash_add_new(&new_hash, key, value);
2230+
} else {
2231+
zend_hash_next_index_insert_new(&new_hash, value);
2232+
}
2233+
} ZEND_HASH_FOREACH_END();
2234+
2235+
Z_ARRVAL_P(stack)->pDestructor = NULL;
2236+
zend_hash_destroy(Z_ARRVAL_P(stack));
2237+
*Z_ARRVAL_P(stack) = new_hash;
22252238

22262239
/* Clean up and return the number of elements in the stack */
22272240
RETVAL_LONG(zend_hash_num_elements(Z_ARRVAL_P(stack)));

0 commit comments

Comments
 (0)