SamDasti
SamDasti

Reputation: 87

Allow empty index of array in foreach loop

Trying to insert data even if any index of array in foreach loop is empty. trying the following script its giving Undefined index: error in case of empty index.

$data = array();
if(count($_POST['data']) > 0 && !empty ($_POST['data'])){  
    foreach($_POST['data'] as $key => $array){
        $row = array();
        $row['team_id'] = intval($array['team_id']);
        $row['Note'] = strip_tags(trim(strval($array['Note'])));
        $row['result'] = strip_tags(trim(strval($array['result'])));
        $data[$key] = $row;
    }
        $sql = $db->prepare("INSERT INTO teams ('team_id','note','result') values (:team_id, :note, :result) ");

        foreach($data as $key => $array){
           $sql->execute(array(':team_id' => $array['team_id'], ':note' =>$array['Note'], ':result' => $array['result'], ));
    }
}

Upvotes: 0

Views: 94

Answers (2)

Niranjan K.
Niranjan K.

Reputation: 21

<?php

$data = array();
foreach ($_POST['data'] as $key => $array) {
    $data[$key]['team_id'] = isset($array['team_id']) ? intval($array['team_id']) : null;
    $data[$key]['Note'] = isset($array['Note']) ? strip_tags(trim(strval($array['Note']))) : null;
    $data[$key]['result'] = isset($array['result']) ? strip_tags(trim(strval($array['result']))) : null;

}

?>

Upvotes: 1

Josep Widtantio
Josep Widtantio

Reputation: 194

You can prevent isset when set in variable

$row['team_id'] = isset($array['team_id']) ? intval($array['team_id']) : null;
$row['Note'] = isset($array['Note']) ? strip_tags(trim(strval($array['Note']))) : null;
$row['result'] = isset($array['result']) ? strip_tags(trim(strval($array['result']))) : null;

Upvotes: 1

Related Questions