PHP Indexed Arrays

Back to ACP page

Table of Contents

PHP 1 Indexed Arrays

<h4>Indexed_Arrays</h4> <p>Create and display an indexed array:</p> <pre> <?php $cars = array("Volvo", "BMW", "Toyota"); var_dump($cars); ?> </pre>

Example 1

Result View Example

PHP 2 Access Indexed Arrays

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]; ?>

Example 2

Result View Example

PHP 3 Change Value

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); ?>

Example 3

Result View Example

PHP 4 Loop Through an Indexed Array

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>"; } ?>

Example 4

Result View Example

PHP 5 Index Number

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>

Example 5

Result View Example

PHP 6 Random Index Number

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>

Example 6

Result View Example

Document

Document in project

You can Download PDF file.

Reference