PHP Array
PHP Array is a special type variable, which is used to store multiple values.
PHP Array holds many values in a single variable at a time.
In PHP, There are two types of the array given :
- One Dimensional Array
- Multidimensional Array
What is the one-dimensional array in php?
A single array called a one-dimensional array this array contains only values.
In PHP, you can save array data in two forms following here :
- Indexed Array
- Associative Array
What is an indexed array?
Whose array contains the numeric index, It is called an indexed array.
In an indexed array, the index always starts from 0.
Syntax of the indexed array
// Here index of value sets automatically
$index_array = array("val 1", "val 2", "val 3", .... , "val n");
or
// Here index of value sets manually
$index_array[0] = "val 1";
$index_array[1] = "val 2";
$index_array[2] = "val 3";
:
:
$index_array[m] = "val n";
Understand Indexed array from this example:
<?php
$sample_array = array("Hello", "my", "name", "is", "john", "will");
// To get the output of the array to pass this array in a loop
$count = count($sample_array ); // count(sample_array ) is the function of count total length of array
for( $i = 0; $i < $count; $i++ )
{
echo "Line => " . $sample_array [$i] . "\n";
}
?>
Output:
Line => Hello
Line => my
Line => name
Line => is
Line => john
Line => will
What is the associative Array?
Whose array contains a named key index, It is called an associative array.
Syntax of the associative Array
$sample_array = array("key 1"=>"data 1", "key 3"=>"data 3", .... , "key n"=>"data n");
or
$sample_array["key 1"] = "data 1";
$sample_array["key 2"] = "data 2";
$sample_array["key 3"] = "data 3";
:
:
$sample_array["key n"] = "data n";
Understand the Associative array from this example:
<?php
$sample_array = array("id"=>"123", "name"=>"john", "age"=>"25", "profession"=>"web developer");
// To get the output of the array to pass this array in a foreach loop
foreach( $sample_array as $key=>$value )
{
echo $key . " is " . $value . "\n";
}
?>
Output:
id is 123
name is john
age is 25
profession is web developer