What can replace this design?

There are a lot of similar checks in the code, but I don’t really want to put it into a separate function and this array is taken after processing the xml file.

if(isset($dict_notification->{'purchaseDocumentation'}->{'grantStartDate'})) { $date = $dict_notification->{'purchaseDocumentation'}->{'grantStartDate'}; } else { return; // old - $date = null; } 
  • one
    Starting from version 5.3, you can write $date = $dict_notification->{'purchaseDocumentation'}->{'grantStartDate'} ?: null; True, if you have false , 0 , '0' , etc. in the variable, then in $date returns NULL :( - Visman
  • @Visman, false , 0 and '0' are quite correct and, possibly, one of the expected options. It is better to check at the very beginning, after parsing, in one crowd (arrays of expected keys, possible markers, etc.). - user207618
  • @Visman yes, this option is suitable, and it is possible to make a way out of the procedure? As an example: $id=$dict_notification->{'id'} ?: return; - users

1 answer 1

or pass it to a separate function; pass an array by reference to it — no problem. Something in the spirit of:

 function turboset(&$array, $key, $default=''){ if (!isset($array[$key])){ return $default; } return $array[$key]; } 

either php7 example from there

 <?php // Fetches the value of $_GET['user'] and returns 'nobody' // if it does not exist. $username = $_GET['user'] ?? 'nobody'; // This is equivalent to: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody'; // Coalescing can be chained: this will return the first // defined value out of $_GET['user'], $_POST['user'], and // 'nobody'. $username = $_GET['user'] ?? $_POST['user'] ?? 'nobody'; ?> 
  • php v 5.6, and would not really like to use the function - users
  • there is no other real way out, IMHO, however, I will follow the development of events - strangeqargo