Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is elements order the same after array being split by array_keys() and array_values()? [duplicate]

Tags:

arrays

php

I looked through the manual pages of both array_keys and array_values. Neither of them said anything about whether they honor the elements order of the original array. All they promise is they will return all the keys or values from the original array. But can we be absolutely sure that the order of the elements will also be exactly the same as that of the original array? No matter what array it is?

I ask this is because I have this:

$record = array('name' => 'Lisa', 'age' => 16, 'gender' => 'female');

$fields = array_keys($record);
$values = array_values($record);

$sql = "INSERT INTO {$this -> table} (".implode(', ', $fields).") VALUES (".implode(', ', array_fill(0, count($fields), '?')).")";
$sth = $this -> dbh -> prepare($sql);
$sth -> execute($values);

While I can use named parameters but it would cost slightly more coding so I prefer this way which requires the elements of $fields and $values are in corresponding pairs, preferably they would be in exactly same order as that of the original array $record.

Any idea?

like image 701
datasn.io Avatar asked Jan 13 '14 13:01

datasn.io


1 Answers

Yes, they are. Indeed, that's not mentioned in manual, so I'm referring to internal implementation. Here's sample for array_keys():

/* Go through input array and add keys to the return array */
    zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos);
    while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) {
        if (search_value != NULL) {
            is_equal_func(&res, search_value, *entry TSRMLS_CC);
            add_key = zval_is_true(&res);
        }

        if (add_key) {
            MAKE_STD_ZVAL(new_val);
            zend_hash_get_current_key_zval_ex(Z_ARRVAL_P(input), new_val, &pos);
            zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &new_val, sizeof(zval *), NULL);
        }

        zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos);
    }

-well, yes, code above is in C, but it definitely shows what's internal logic inside the function. I think lxr is very friendly for search - so I omit such things as macro-definitions (they are off this question) - but you can go deeper and investigate full picture.

like image 128
Alma Do Avatar answered Sep 27 '22 20:09

Alma Do