Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to an array only if a variable is set [duplicate]

Tags:

php

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']
    );
like image 782
Callombert Avatar asked Oct 20 '14 14:10

Callombert


2 Answers

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.]
);
like image 70
Patrick Moore Avatar answered Sep 22 '22 06:09

Patrick Moore


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"');
like image 30
Eujinks Avatar answered Sep 23 '22 06:09

Eujinks