Pages

Thursday, August 20, 2009

PHP mixed arrays

I wanted to verify that I could mix scalar data and array data in the same array. Here's what I came up with.

$test_array=array(
'first'=>'1',
'second'=>'2',
'array1'=>array('begin'=>'one','middle'=>'2','end'=>'three'),
'array2'=>array('a','b','c')
);

echo ("first is {$test_array['first']}
");
echo ("second is {$test_array['second']}
");
echo ("array1 begin is {$test_array['array1']['begin']}
");
echo ("array1 middle is {$test_array['array1']['middle']}
");
echo ("array1 end is {$test_array['array1']['end']}
");
$count=0;
foreach ($test_array['array2'] as $value){
echo("array2 key $count is $value
");
$count++;
}
?>

The output was:
first is 1
second is 2
array1 begin is one
array1 middle is 2
array1 end is three
array2 key 0 is a
array2 key 1 is b
array2 key 2 is c


This means we can use mixed data in one array and access the scalar and composite data as expected.

No comments: