raheel shan raheel shan - 3 months ago 11
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

if(isset($domain['title'])){
$data['title'] = $domain['title'];
}


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

Answer

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];
  }
}