views:

48

answers:

3

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

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

something($data);

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

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

+1  A: 

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.

Cassy
+1  A: 

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

deceze
A: 

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
    }
}
SpawnCxy