Arrays are complex variables that allow us to store a set of values under more than one value or single variable name. Let's say you want to store the colors in your PHP script. By storing one in one color in one variable, something like this can be seen:
Syntax -
<?php
$color1 = "Red";
$color2 = "Green";
$color3 = "Blue";
?>
Types of Arrays in PHP
There are three types of arrays that you can create. These are:
- Indexed array — An array with a numeric key.
- Associative array — An array where each key has its own specific value.
- Multidimensional array — An array containing one or more arrays within itself.
Indexed Array
The PHP index starts with the number that starts at 0. We can store numbers, strings, and objects in PHP arrays. All PHP array elements are assigned by default in an index number.
Syntax 1-
$season=array("summer","winter","spring","autumn");
Syntax 2-
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Example 1-
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Example 2 -
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Associative Array
In an associative array, the keys assigned to values can be arbitrary and user-defined wires. In the following example, the array uses keys instead of index numbers:
Syntax -
<?php
// Define an associative array
$ages = array("Peter"=>22, "Clark"=>32, "John"=>28);
?>
// Define an associative array
$ages = array("Peter"=>22, "Clark"=>32, "John"=>28);
?>
Example -
<?php
$ages["Peter"] = "22";
$ages["Clark"] = "32";
$ages["John"] = "28";
?>
$ages["Peter"] = "22";
$ages["Clark"] = "32";
$ages["John"] = "28";
?>
Multidimensional Arrays
The multi-dimensional array is an array in which each element can also have an array, and in the sub-array, each element can be an array or array may be further and inside it.
Example -
<?php
// Define a multidimensional array
$contacts = array(
array(
"name" => "Peter Parker",
"email" => "peterparker@mail.com",
),
array(
"name" => "Clark Kent",
"email" => "clarkkent@mail.com",
),
array(
"name" => "Harry Potter",
"email" => "harrypotter@mail.com",
)
);
// Access nested value
echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
?>
0 comments:
Post a Comment