PHP Array
Array work like a variable array is used to stores one or more similar type of values in a single variable. Example if you want to store 50 numbers then instead of defining 100 variables it is easy to define an array of 50 length.
In a single defination array is used to stores multiple values in one single variable:
<?php
$cars = array("Maruti", "Tata", "Toyota");
echo "My best car is= " . $cars[0] . "," . $cars[1] . " and " . $cars[2] . ".";
?>
array() function is used to create an array in PHP:
example array();
There are three types of arrays in PHP:
Numeric /Indexed arrays – Arrays with a numeric index ,index array start with zero
Example:
<?php
/* Method one */
$exam[0] = "first";
$exam[1] = "second";
$exam[2] = "three";
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
/* Method two*/
$numbers = array( 11, 22, 33);
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
?>
Associative arrays – Arrays used string as index (key)
<?php
/* Method First. */
$salaries['Shiv'] = "First";
$salaries['Amit'] = "Second";
$salaries['Rohit'] = "Third";
echo "Result Of Shiv is ". $salaries['Shiv'] . "<br />";
echo "Result Of Amit is ". $salaries['Amit']. "<br />";
echo "Result Of Rohit is ". $salaries['Rohit']. "<br />";
/* Method Second For Associate array */
$marks = array("Amit" => 200, "Rohit" => 150, "Shiv" => 500);
echo "Marks of Amit is ". $marks['Amit'] . "<br />";
echo "Marks of Rohit is ". $marks['Rohit']. "<br />";
echo "Marks of Shiv is ". $marks['Shiv']. "<br />";
?>
Multidimensional arrays – When arrays containing more arrays and values
<?php
$marks = array(
“Shiv” => array (
“physics” => 77,
“maths” => 60,
“chemistry” => 59
),
“Amit” => array (
“physics” => 50,
“maths” => 52,
“chemistry” => 49
),
“Rohit” => array (
“physics” => 55,
“maths” => 32,
“chemistry” => 33
)
);
/* Accessing multi-dimensional array values */
echo “Marks for Shiv in physics : ” ;
echo $marks[‘Shiv’][‘physics’] . “<br />”;
echo “Marks for Amit in maths : “;
echo $marks[‘Amit’][‘maths’] . “<br />”;
echo “Marks for Rohit in chemistry : ” ;
echo $marks[‘Rohit’][‘chemistry’] . “<br />”;
?>