|
Posted by Paul Lautman on 07/06/06 09:16
Markus Ernst wrote:
> Hi
>
> While looping through an array I extract all keys on the fly, as in
> this example:
>
> $data = array(
> array('name' => 'Helen', 'age' => '40'),
> array('name' => 'Mark', 'email' => 'mark@xyz.com', 'age' => '90'),
> );
> $keys = array();
> foreach ($data as $row) {
> foreach ($row as $key => $value) {
> // do other things here
> $keys[$key] = 1;
> }
> }
> $column_names = array_keys($keys);
>
> Now my question is about the line
> $keys[$key] = 1;
>
> This overwrites existing entries and thus creates a set of unique
> keys. This could also be done without overwriting:
> if (!isset($keys[$key])) $keys[$key] = 1;
>
> So I wonder which is more efficient - overwriting the array entry at
> every loop, or checking for it with the if statement.
>
> Thanks for a comment
> Markus
ISTR a general rule that said that assignments were more efficienct that
tests.
If this is not the case, then the answer to your question depends on whether
in most cases you will end up doing the assignment, or whether in most cases
the value is already set.
If the former is true, then it is certainly not more efficient, if the
latter then it may be. This is where knowing something about the data is
required.
I think that all makes sense!
[Back to original message]
|