开发者

function with array variable

开发者 https://www.devze.com 2023-01-02 10:57 出处:网络
How do I pass an array through a function, for example: $data = array( \'color\'=> \'red\', \'height\' => \'tall\'

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

精彩评论

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