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]?
asked Jun 8, 2010 at 6:11
CruisinCosmo
1,15715 silver badges36 bronze badges
-
Do you mean you need the function to be able to modify the array?user180100– user1801002010年06月08日 06:15:14 +00:00Commented 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 functionCruisinCosmo– CruisinCosmo2010年06月08日 06:17:16 +00:00Commented Jun 8, 2010 at 6:17
-
you have your function already. what's the problem with it?Your Common Sense– Your Common Sense2010年06月08日 06:21:15 +00:00Commented 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?CruisinCosmo– CruisinCosmo2010年06月08日 06:23:36 +00:00Commented Jun 8, 2010 at 6:23
-
Quotes are missing around color in the if. Could be your problem.user180100– user1801002010年06月08日 06:27:35 +00:00Commented Jun 8, 2010 at 6:27
3 Answers 3
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.
answered Jun 8, 2010 at 6:25
Dan Soap
10.3k2 gold badges43 silver badges50 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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'].
answered Jun 8, 2010 at 6:31
Comments
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
}
}
answered Jun 8, 2010 at 6:33
Young
8,4627 gold badges47 silver badges65 bronze badges
Comments
lang-php