Jump to content

[SOLVED] Quick Question


lewis987

Recommended Posts

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

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 />';
}

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...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.