开发者

function with array variable

How do I pass an array through a function, for example:

$data = array(
    'color'  => 'red',
    'height' => 'tall'
);

somethi开发者_运维百科ng($data);

function something($data) {
    if ($data['color'] == 'red') {
        // do something
    }
}  

how can I get the function to recognize $data[color] and $data[height]?


Sometimes the easiest answer is the right one:

$data = array(
    'color'  => 'red',
    'height' => 'tall'
);


function something($data) {
    if ($data['color'] == 'red') {
        // do something
    }
} 

something($data);

Arrays don't need a special handling in this case, you can pass any type you want into a function.


This works:

$data = array('color'  => 'red', 'height' => 'tall');

function something($data) {
    if ($data['color'] == 'red') {
        // do something
    }
}

something($data);

As remark, you need to quote your strings: $data['color'].


Maybe you need to make some validations to the parameter to make the function more reliable.

function something($data)
{
    if(is_array(data) and isset($data['color']))
    {
         if($data['color'] == 'red')
         {
            //do your thing
         }
    }
    else
    {
         //throw some exception
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜