Array

PHP Array

A PHP array is a data structure like other language that stores one or more similar type of values in a single value. An array is created using an "array()" function in PHP.The PHP arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key.

PHP array are three type:-

Indexed or Numeric Arrays

PHP indexed or Numeric is represented by number which starts from 0.Values are stored and accessed in linear fashion.

Example

<?php
$fruite[0]="Apple";
$fruite[1]="guava";
$fruite[2]="grapes";
$fruite[3]="mango";
echo "fruite are: $fruite[0], $fruite[1], $fruite[2] and $fruite[3]";
?>

Output

fruite are: Apple, guava, grapes and mango

Associative Arrays

Associative array will have their index as string so that you can establish a strong association between key and values.We can associate name with each array elements in PHP using => symbol.

Example

<?php
$weight = array("Apple"=>"3.", "Ben"=>"5", "grapes"=>"4");
echo "fruite is " . $weight['Apple'] . " kg";
?>

Output

fruite is 3. kg

Multidimensional Arrays

PHP multidimensional array is also known as array of arrays.Values in the multi-dimensional array are accessed using multiple index.

Example

<?php
$food =array(
"fruite" => array("Apple", "grapes"),
"vegetables" => array("broccoli", "corn")
);
print_r($food)
?>

Example

Array ( [fruite] => Array ( [0] => Apple [1] => grapes ) [vegetables] => Array ( [0] => broccoli [1] => corn ) )