Most efficient way to assign optional value to a variable

I inherited a WordPress project and am currently writing a script to export database tables in .csv format. The original designer stored a lot of custom information about each user in the wp_usermeta table. Unfortunately, a lot of this information was optional, and in the case of NULL optional data, the row in the database just does not exist. An example for users with an optional “gender” field:

umeta_id user_id meta_key meta_value
1        1       gender   1
2        1       phone    5555555555
3        1       address  "123 alphabet lane"

4        2       phone    5555551234
5        2       address  "123 alphabet way"

6        3       gender   2
...

I can’t have missing fields with a .csv, or the formatting would look weird, so I need to check each user’s info for these missing fields and insert an empty string. Since I will be iterating over tens of thousands of database rows, I was curious which method of variable assignment was the most efficient in terms of memory usage and execution time to do this.

Read More

Method 1

if (empty($fetched[$field]))
{
    $data[$field] = '';
}
else
{
    $data[$field] = $fetched[$field];
}

Method 2

$data[$field] = '';
if (! empty($fetched[$field])
{
    $data[$field] = $fetched[$field];
}

Method 3

$data[$field] = empty($fetched[$field]) ? '' : $fetched[$field];

Or are they all close enough that it really doesn’t make a difference? Thanks in advance for any insight you may offer!

Related posts

Leave a Reply

1 comment

  1. They all close enough that it really doesn’t make a difference. Bot even slightest.

    No syntax issue ever affects performance

    It is

    • algorithms (a loop of 100500 iterations)
    • data manipulations (looking through a file of 500Mb)
    • network lookups (checking RSS feeds for the every page request)
    • heavy calculations (image resizing)

    affect performance.

    But no syntax issue ever. Not whatever syntax issue. Never. Neither measurable nor theoretical difference.