php – Error executing Fields checklist

Question:

I have the following code:

$funcionario_materiais = array();
foreach($_POST AS $key=>$val){
    $tmp = explode("_",$key);
    if($tmp[0]=="materiais"){
        $funcionario_materiais[$tmp[1]]=$val;
        unset($_POST[$key]);
    }
}

$funcionario_materiais_novo = array();
for($i=0;$i<count($funcionario_materiais['material']);$i++){
    foreach($funcionario_materiais as $key=>$val){
        $funcionario_materiais_novo[$i][$key]= $funcionario_materiais[$key][$i];
        $funcionario_materiais_novo[$i]['idFuncionario'] = $ultimo_id;
        $funcionario_materiais_novo[$i]['data'] = date('Y-m-d', strtotime($funcionario_materiais_novo[$i]['data']));                
    }
}

But when it's time to run, it gives an error:

A PHP Error was encountered

Severity: Notice
Message: Undefined index: date
Filename: controllers/official.php
Line Number: 246

This is line 246:

$funcionario_materiais_novo[$i]['data'] = 
    date('Y-m-d', strtotime($funcionario_materiais_novo[$i]['data']));

I think it's because within the fields, some were filled and others weren't.
Because it's an array , and it can be filled or not. But I don't know how to check if the field is filled or not, inside the foreach
If anyone can help, I really appreciate it!

Answer:

// verifica se existe a posição no array
if (array_key_exists("data", $funcionario_materiais_novo[$i])) {
        // seu codigo
        $funcionario_materiais_novo[$i]['data'] = date('Y-m-d', strtotime($funcionario_materiais_novo[$i]['data']));
}

Put this inside your foreach. This should work. 🙂

Scroll to Top