Wednesday, December 29, 2010

array in php

array_combine: php 5.x

This function takes two arrays and puts them together, though not in the way you might think at first. This function takes the first array and uses it as the keys for your new array. It then takes the second array and uses it as the values for your new array. It is important to ensure that both of your input arrays have the same number of elements. If they don’t, the function will return boolean FALSE rather than returning your new array.

$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>
The above example will output:

Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)


array_flip — Exchanges all keys with their associated values in an array

$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>
now $trans is:

Array
(
[1] => b
[2] => c
)

array_product — Calculate the product of values in an array


$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";

?>
The above example will output:

product(a) = 384

array_merge — Merge one or more arrays
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
The above example will output:

Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)

No comments:

Post a Comment