if语句和函数参数

I have a function I have to fill out, and the only way I can see doing it is a mess. The function I have is:

public function($keys = array(), $pages = array()){}

Essentially the goal is:

  • If keys are an array and each key is not set, do something.
  • If Keys are not an array and are not set, do something.

The same concept goes for pages.

so that's four if statements, then we do:

If key is array but pages is not, if pages is array but key is not. if both are arrays....

What I have so far is:

public function sidebar($keys = array(), $pages = array()){
    $builder = AisisCore_Factory_Pattern::create('AisisCore_Template_Builder');

    if(is_array($keys)){
        foreach($keys as $key){
            if(!$builder->get_specific_option($key)){
                get_sidebar();
            }
        }
    }else{
        if(!$builder->get_specific_option($keys)){
            get_sidebar();
        }
    }

    if(is_array($pages)){
        foreach($pages as $page){
            if(!$page){
                get_sidebar();
            }
        }
    }else{
        if(!$pages){
            get_sidebar();
        }
    }

}

You can see its quickly becoming a mess. get_specific_option will check if that key exists. arrays are done like: array('key', 'secondKey') and so on. pages are done as such: array(is_page(), is_category()) - each of those returns true or false, hence the boolean check. get_sidebar() will get the sidebar if, say for example, a key is not set, or a page does not equal true.

I am not sure how to create this function with out it being a disaster. Can some one help?

You can remove A LOT of complexity by always converting to an array (quick one-liner)

$keys = is_array($keys) ? $keys : ($keys ? array($keys) : array());
$pages = is_array($pages) ? $pages : ($pages ? array($pages) : array());

Your function now:

public function sidebar($keys = array(), $pages = array()){
    $builder = AisisCore_Factory_Pattern::create('AisisCore_Template_Builder');
    $keys = is_array($keys) ? $keys : ($keys ? array($keys) : array());
    $pages = is_array($pages) ? $pages : ($pages ? array($pages) : array());

    foreach ($keys as $key) {
        if (!$builder->get_specific_option($key)) {
            get_sidebar();
        }
    }

    foreach ($pages as $page) {
        if (!$page) {
            get_sidebar();
        }
    }
}

This seems like a lot of potential sidebar inclusions. Just saying. But, you can pass NULL for either of the two parameters and it won't run the foreach contents at all.

You can provide the value as null if the option is optional such as:

public function sidebar($keys = NULL, $pages = NULL){
  //Do something here
}

Might this will work for you;

<?php
    $search_array = array(
              'first' => 1, 
              'second' => 4);
    if (array_key_exists('first', $search_array)) {
         echo "The 'first' element is in the array";
    }
?>