0

I have updated PHP 7.3 to version 8.1 but with the following code, I get a warning:

$this->m_intEventId = 
    $this->m_objMaintenanceRequest->getEventIds()[CEventSubType::WORKORDER_STATUS_UPDATED] 
        ?? $this->m_objMaintenanceRequest->getEventIds()[CEventSubType::WORKORDER_CLOSED] 
        ?? $this->m_objMaintenanceRequest->getEventIds()[CEventSubType::WORKORDER_CLOSED_AND_WORK_COMPLETED] 
        ?? $this->m_objMaintenanceRequest->getEventIds()[CEventSubType::WORKORDER_COMPLETED];

The warning is

Trying to access array offset on value of type null

We can use isset(), but in this case, do we need to check individual index with isset()? Is there a way to resolve this issue?

Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
  • My guess is, that one of the values returned by `$this->m_objMaintenanceRequest->getEventIds()` is `null`. If you then try to access the element at the given index, the warning is thrown. – mamen Feb 16 '23 at 12:08
  • Does this answer your question? [Message: Trying to access array offset on value of type null](https://stackoverflow.com/questions/59336951/message-trying-to-access-array-offset-on-value-of-type-null) – mamen Feb 16 '23 at 12:11
  • No doubt this is similar question but with different use case. My point it to addressed multiple conditions with isset. Is there way to resolve it ? – user18435906 Feb 16 '23 at 12:14

1 Answers1

0

Without more information, my guess is that one of the values returned by $this->m_objMaintenanceRequest->getEventIds() is null. If you then try to access the element at the given index, the warning is thrown.

You have to check for null first using isset(). For example:

function GetEventIdOfType($eventIds, $type) {
   if(isset($eventIds[$type])) {
      return $eventIds[$type];
   }

   return null;
}

$eventIds = $this->m_objMaintenanceRequest->getEventIds();

$this->m_intEventId = 
    GetEventIdOfType($eventIds, CEventSubType::WORKORDER_STATUS_UPDATED) 
        ?? GetEventIdOfType($eventIds, CEventSubType::WORKORDER_CLOSED)  
        ?? GetEventIdOfType($eventIds, CEventSubType::WORKORDER_CLOSED_AND_WORK_COMPLETED) 
        ?? GetEventIdOfType($eventIds, CEventSubType::WORKORDER_COMPLETED);

I did not test this code, but I think you get the idea. I also am assuming that only one of the array elements is set. If for example CEventSubType::WORKORDER_STATUS_UPDATED and CEventSubType::WORKORDER_COMPLETED are set, only the first is returned.

mamen
  • 1,202
  • 6
  • 26