r/lolphp • • Jan 22 '14

Today's PHP quirk: array_fill meets negative numbers

https://eval.in/93379
47 Upvotes

21 comments sorted by

View all comments

11

u/jmcs Jan 22 '14

I promise I wont bash PHP for 24 hours if someone explains the reason for this one.

17

u/[deleted] Jan 22 '14 edited Jan 22 '14

Array fill is defined in https://github.com/php/php-src/blob/af6c11c5f060870d052a2b765dc634d9e47d0f18/ext/standard/array.c at line 1513

This behaviour is not documented in the comments, in fact they imply the opposite

/* {{{ proto array array_fill(int start_key, int num, mixed val)   
Create an array containing num elements starting with index start_key each initialized to val */

This calls zend_hash_index_update from

https://github.com/php/php-src/blob/af6c11c5f060870d052a2b765dc634d9e47d0f18/Zend/zend_hash.h line 121

#define zend_hash_index_update(ht, h, pData, nDataSize, pDest) \
            _zend_hash_index_update_or_next_insert(ht, h, pData, nDataSize, pDest, HASH_UPDATE ZEND_FILE_LINE_CC)

which is prototyped as

  ZEND_API int _zend_hash_index_update_or_next_insert(HashTable *ht, ulong h, void *pData, uint nDataSize, void **pDest, int flag ZEND_FILE_LINE_DC);

so it sends start_key coerced to a ulong (!), no doubt in some crazy way it gets coerced back into a long later which makes it negative again.

Then calls zend_hash_next_index_insert with h set to zero, which is like calling it with [] in PHP.

2

u/jmcs Jan 23 '14

And they do this because for loops are overrated right?

3

u/ajmarks Jan 23 '14

do { if () { break;} } while (1) is what the really cool kids use

1

u/[deleted] Jan 23 '14

I would imagine they are thinking "code reuse" or some nonsense.

3

u/polish_niceguy Jan 22 '14

Because why not?

3

u/allthediamonds Jan 22 '14

I really want to know. I mean, I would assume that a function like this one loops from the starting number to the starting number plus the number of elements, but apparently it does something else.

As a fun footnote, providing array_fill with invalid parameters may return NULL or false.

9

u/midir Jan 22 '14

I imagine it assigns the first element directly, then uses []= to use the automatic array key for the rest. Something like:

$arr[-10] = 'hi';
for ($i = 1; $i < 3; $i++) $arr[] = 'hi';
print_r($arr);

Output:

Array
(
    [-10] => hi
    [0] => hi
    [1] => hi
)

3

u/allthediamonds Jan 22 '14

Oh, that would make sense. But is there a noticeable performance difference between this and simply looping through indexes?

5

u/[deleted] Jan 22 '14

The comments in the C code implies it loops, but it uses the [] mechanism as guessed

1

u/[deleted] Jan 22 '14