Table of Contents
<h4>Indexed_Arrays</h4>
<p>Create and display an indexed array:</p>
<pre>
<?php
$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
?>
</pre>
Result View Example
To access an array item you can refer to the index number.
<h4>Access_Indexed_Arrays</h4>
<p>To access an array item you can refer to the index number.</p>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[0];
?>
Result View Example
To change the value of an array item, use the index number:
<h4>Change_Value</h4>
<?php
$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
var_dump($cars);
?>
Result View Example
To loop through and print all the values of an indexed array, you could use a foreach loop, like this:
<h4>Loop_Through_an_Indexed_Array</h4>
<?php
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as $x) {
echo "$x <br>";
}
?>
Result View Example
The key of an indexed array is a number, by default the first item is 0 and the second is 1 etc., but there are exceptions.
New items get the next index number, meaning one higher than the highest existing index.
<h4>Index_Number</h4>
<p>if you use the array_push() function to add a new item, the new item will get the index 3:</p>
<pre>
<?php
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
array_push($cars, "Ford");
var_dump($cars);
?>
</pre>
Result View Example
If you assign a new value without an index number, PHP will automatically assign one for you.
<h4>Random_Index_Number</h4>
<pre>
<?php
$cars[5] = "Volvo";
$cars[7] = "BMW";
$cars[14] = "Toyota";
array_push($cars, "Ford");
var_dump($cars);
?>
</pre>
Result View Example
Document in project
You can Download PDF file.