raheel shan raheel shan -4 years ago 145
PHP Question

don't initialize variable if isset returns false

I have a simple statement like this:

$data['title'] = isset($domain['title']) ? $domain['title'] : '';

This is ok. The data array is then used in an insert query using codeigniter active record. Now I wanted to ask is there a way that if isset returns false, then don't initialize $data['title'].

I know the alternative here

$data['title'] = $domain['title'];

I want to know how can we do the same
with the upper instruction?

Answer Source

You could do this, but use if is more readable.

isset($domain['title']) && ($data['title'] = $domain['title']);

Edit: Example of using a loop.

foreach (array('title', 'body', 'footer') as $key) {
  if (isset($domain[$key])) {
   $data[$key] = $domain[$key];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download