Monday, May 9, 2016

WDP - PHP Arrays


PHP Arrays

Explain
An array in PHP is actually an ordered map. A map is a type that associates values to keys.

Syntax
array(
key => value,
key2 => value2,
key3 => value3,
)

Example code and output
<?php

$array = array(
"John" => "16 Years old",
"Barney" => "21 Years old",
);

?>

Types of Arrays


Indexed arraysArrays with numeric index


SYNTAX
array(value1,value2,value3,etc.);

Associative arrays
Arrays with named keys
SYNTAX
array(key=>value,key=>value,key=>value,etc.);

Example code and output

<?php

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";

?>

OUTPUT
Peter is 35 years old


Multidimensional arrays
Arrays containing one or more arrays
SYNTAX

$array = array (
array (value1, value2, value3),
array (value1, value2, value3),
array (value1, value2, value3),
);

EXAMPLE CODE & OUTPUT

<?php

// A two-dimensional array:
$cars=array
(
array("Volvo",100,96),
array("BMW",60,59),
array("Toyota",110,100)
);

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
?>


Reference:

http://php.net/manual/en/language.types.array.php

http://www.w3schools.com/php/func_array.asp



No comments:

Post a Comment