Skip to content
Advertisement

php array, error when filtering array and the value is not present

I’m trying to use isset to check if the $filtered_data returns a set of data.

I’m using this code rather than foreach because datasetID is a unique id.

My novice understanding is that if (isset($filtered_data)) returns true or false? So the if mrans that if records are returned do x. So, currently when I put in $lastPart = '5fd4058e5c8d2' I’m getting the expected result. When I change the 2 to a 3 (a non-existing ID) $lastPart = '5fd4058e5c8d3' I get Undefined index: 5fd4058e5c8d3`.

I expect the isset is doing its job and the error is thrown on this line as indicated in the error message $filtered_data = array_column(array_merge(...$data), null, 'datasetID')[$lastPart]; am I missing the obvious? I guess this needs a get out clause if the value $lastPart does not exist in the array?

$filtered_data = array_column(array_merge(...$data), null, 'datasetID')[$lastPart];

if (isset($filtered_data)){
  echo 'qwertyuio';
  $datasetID = $filtered_data['datasetID'];
  $collectionCode = $filtered_data['collectionCode'];
  $datasetName = $filtered_data['datasetName'];
  $ownerInstitutionCode = $filtered_data['ownerInstitutionCode'];
  $vernacularName = $filtered_data['vernacularName'];
  $elementName = strtolower($filtered_data['elementName']);
} else {
  echo 'not set';
}

Advertisement

Answer

A quick fix would be to use null coalescing (??) and setting the value to a dummy value if not found, then your isset() can be reworked to check for the dummy value…

$filtered_data = array_column(array_merge(...$data), null, 'datasetID')[$lastPart] 
                  ?? null;

if ($filtered_data){
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement