lewis987 Posted October 14, 2008 Share Posted October 14, 2008 Im trying to optimize some code i've written up, the thing is, i need to check if an array that is sent to a function has the right keys set. At the minute im using an if elseif statement and it looks ugly. Im wondering if its faster and more practical settings a numbered array with the names of keys that are required and checking it in a loop. Is that more practical? Link to comment https://forums.phpfreaks.com/topic/128400-solved-quick-question/ Share on other sites More sharing options...
wildteen88 Posted October 14, 2008 Share Posted October 14, 2008 You could do $require_keys = array('key1', 'key2', 'key3'); $input_array = array('key1' = > 'Hello', 'key3' => 'World'); foreach($required_keys as $key) { // check that the key exists in the input array if(isset($input_array[$key])) { echo $key . ' exists'; } else { echo $key . ' DOES NOT exists'; } echo '<br />'; } Link to comment https://forums.phpfreaks.com/topic/128400-solved-quick-question/#findComment-665254 Share on other sites More sharing options...
lewis987 Posted October 14, 2008 Author Share Posted October 14, 2008 I was thinking something like this: $requiredVars = array("location", "file_types", "dir", "temp_dir", "get_var_1", "get_var_2", "get_var_3"); $arrayCount = count($requiredVars); for($i = 0; $i < $arrayCount; $i++){ if(empty(trim($VAR[$requiredVars[$i]]))){ return false; } } It has the same effect... Link to comment https://forums.phpfreaks.com/topic/128400-solved-quick-question/#findComment-665271 Share on other sites More sharing options...
wildteen88 Posted October 14, 2008 Share Posted October 14, 2008 Yes you could use that. Mine was just an example. I personally prefer to use a foreach loop when looping through arrays. Link to comment https://forums.phpfreaks.com/topic/128400-solved-quick-question/#findComment-665284 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.