I have this array I'm doing like so:
Turns out some of those var aren't always set which cause undefined index issues when trying to inserting it into the db?
Is there a quick way to check each value is set before adding it to the array?
$show_insert = array(
'title' => $show_data['title'],
'thetvdb_id' => $show_data['tvdbid'],
'release_date' => $show_data['FirstAired'],
'lastupdatethetvdb' => $show_data['lastupdatethetvdb'],
'moviedb_id' => $show_data['moviedb_id'],
'imdb_id' => $show_data['IMDB_ID'],
'img_id' => $show_data['tvdbid'],
'media_type' => 1,
'status' => $show_data['status'],
'length' => $show_data['runtime'],
'network' => $show_data['network'],
'overview' => $show_data['overview'],
'seasons' => $show_data['seasons'],
'episodes' => $show_data['episodes'],
'homepage' => $show_data['homepage'],
'last_airdate' => $show_data['last_air_date'],
'vote_average' => $show_data['vote_average']
);
You can use the ternary operator and isset(). We're checking if the variable and key are set (the part before ?). If it is set, use that variable (the part between ? and :) and if not, set to blank (the part after :).
Ternary operator works like:
$variable = ( comparison ? if true : if false );
Thus:
$show_insert = array(
'title' => ( isset( $show_data['title'] ) ? $show_data['title'] : '' ),
'thetvdb_id' => ( isset( $show_data['tvdbid'] ) ? $show_data['tvdbid'] : '' ),
[etc.]
);
if (isset($show_data['title']) {
$show_insert[title] = $show_data['title'];
}
This basically means that if $show_data[title] has been initialized then it will add it to the $show_insert array under the key 'title', if it has not been set, nothing will happen so there will be no array key 'title'
or for large arrays you could have:
public function check_set($array, $variable = null, $key_name)
if ($variable != null) {
$array[$key_name] = $variable;
}
check_set($show_insert, $show_data[title], $title = '"title"');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With