Array is a collection of multiple values in a single variable.
You can access these values to calling a index number.
you can create an array with the help of array() function.
There are three types of Array in PHP.
1. Indexed Array
2. Associative Array
3. Multidimesional Array
<h3>1. Indexed Array</h3>
We can store a multiple courses name is single values.
Example:
<?php
$courses = array("HTML", "CSS", "PHP");
echo "I'm Interested in ". $courses[0];
echo "<br>";
echo "I'm Interested in ". $courses[2];
//$courses[0] mean HTML
?>
Output:
I'm Interested in HTML
I'm Interested in PHP
You can also use array with loop like:
<?php
$lang = array("HTML", "CSS", "PHP");
//count function return the number of values
for($x = 0; $x < count($lang); $x++) {
echo $lang[$x]. "<br>";
}
?>
Output:
HTML
CSS
PHP
<h3>2. Associative Array</h3>
<?php
$lang = array("HTML"=>2000, "CSS"=>3000, "PHP"=>5000);
echo "PHP Fee: ". $lang["PHP"];
?>
Output:
PHP Fee:
You can also use associative array with loop like:
<?php
$lang = array("HTML"=>2000, "CSS"=>3000, "PHP"=>5000);
foreach($abc as $lanuage => $language_fee) {
echo "Language=".$lanuage.",Fe= ".$language_fee."<br>";
}
?>
Output:
Language = HTML, Fee = 2000
Language = CSS, Fee = 3000
Language = PHP, Fee = 5000
<h3>3. Multidimensional Array</h3>
Multidimensional array is also known as two-dimensional array.
A multidimensional array is an array to hold one or more arrays.
In multimensional array we can use indexed and associative
both array at a same time.
Example:
<?php
$courses = array(
"web design" => array("HTML", "CSS", "JavaScript"),
"development" => array("PHP", "MySQL", "Wordpress"));
echo $courses["web design"][0];
echo $courses["web design"][1];
echo $courses["web design"][2];
?>
Output:
HTML
CSS
JavaScript
you can also use multidimensional array with nested loop
<?php
for ($row = 0; $row < 2; $row++) {
for ($col = 0; $col < 3; $col++) {
echo $courses[$row][$col]."<br>";
}
}
?>
Output:
HTML
CSS
JavaScript
PHP
MySql
Wordpress