1

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]?

6
  • Do you mean you need the function to be able to modify the array? Commented Jun 8, 2010 at 6:15
  • I need the function to understand that $data[color] equals red. So that I can use: if ($data[color] == 'red') { do something } inside the function Commented Jun 8, 2010 at 6:17
  • you have your function already. what's the problem with it? Commented Jun 8, 2010 at 6:21
  • I edited the post so that it hopefully makes a bit more sense. Does what I have look correct? Commented Jun 8, 2010 at 6:23
  • Quotes are missing around color in the if. Could be your problem. Commented Jun 8, 2010 at 6:27

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.