Friday, February 11, 2011

PHP Accessing an array element by its index as string literal, good or bad?

$array = array(
  'first element',
  'second element',
  'third element',
);

echo $array['1'];
echo $array[1];

They both produce the same result.

I am asking this question because I noticed for example drupal accesses the index as string literals, where as php.net uses integers.

Are there advantages of one over the other?

Of course I know why $array[foo] is bad.

  • It's indifferent in terms of semantics.

    When you do $array['string'] and 'string' is a number in base 10 without leading zeros and decimal point that fits on the integer range (i.e., is between -PHP_INT_MAX-1 and PHP_INT_MAX), it will be converted into an integer.

    In terms of performance, it's preferrable to use an integer directly because that will skip the conversion step.

    Sean : You beat me to it. That's precisely my sentiments.
    tilman : Kind of what i suspected, but thanks for the 'scientific' explanation. Will wait a bit longer and see what others say. There must be a reason why drupal does it the other way, right?
    dkamins : I would go further and say that accessing an array by stringified numeric index (as OP claims Drupal does) is not only wasted CPU cycles but poor programming style as well. It looks like an attempt to use an array as a hashmap.
    From Artefacto
  • PHP will just coerce the '1' to an integer, or array key 0x01.

    In theory, it would be faster to just access the keys, if they're just a simple array like the one you have posted, with their integer values.

    tilman : When would it not be faster, then?
    Sean : Directly accessing the keys by integer (just a 1) would be faster than by string ('1'). Why? It's less PHP has to do to convert them to binary! It wouldn't be faster if you have a dictionary (where the keys are actually stored as **strings** themselves.)
    From Sean
  • The two forms are identical to the point that one will overwrite the other if they are used to assign values... for example:

    <?php
    $new = array(1 => "number", "1" => "string");
    
    echo count($new); // <== Output: 1
    
    echo "The array has {$new[1]} and {$new['1']}"; 
    //Output: The array has string and string
    
    ?>
    

    Live example


    Theoretically the one where the server does less work is faster. Since no type coercion is necessary with $array[1], that's faster.

0 comments:

Post a Comment