note 115912 deleted from function.array-key-exists by crell

From: Date: Wed, 29 Jun 2022 20:42:07 +0000
Subject: note 115912 deleted from function.array-key-exists by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218759@lists.php.net to get a copy of this message
Note Submitter: ellert at vankoperen dot nl ---- While working with large JSON datastructures I encountered an increasing need to check the presence of certain data all over the place. This led to the function below that lets you simply access the data, and returns it if available, null if not. Note that it uses a variable number of parameters, you can go as deep into a nested structure as you want. <?php function safe_array_access($ar){ $numargs = func_num_args(); $arg_list = func_get_args(); $aritterator = $ar; for($i = 1; $i < $numargs; $i++){ if (isset($aritterator[$arg_list[$i]]) || array_key_exists($arg_list[$i], $aritterator)){ $aritterator = $aritterator[$arg_list[$i]]; }else{ return(false); } } return($aritterator); } ?> Usage: Instead of $a['b']['c'] use safe_array_access($a, 'b', 'c');

« previous php.notes (#218759) next »