PHP Associative Arrays

Back to ACP page

Table of Contents

PHP 1 Associative_Arrays

Associative arrays are arrays that use named keys that you assign to them.

<h4>Associative_Arrays</h4> <pre> <?php $car = array("brand" => "Ford", "model" => "Mustang", "year" => 1964); var_dump($car); ?> </pre>

Example 1

Result View Example

PHP 2 Access Associative Arrays

You can access the values of the array using the key name.

<h4>Access_Associative_Arrays</h4> <?php $car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964); echo $car["model"]; ?>

Example 2

Result View Example

PHP 3 Change Value

You can change the value of a specific element by referring to the key name.

<h4>Change_Value</h4> <?php $car = array("brand" => "Ford", "model" => "Mustang", "year" => 1964); $car["year"] = 2024; var_dump($car); ?>

Example 3

Result View Example

PHP 4 Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a foreach loop, like this:

<h4>Loop_Through_an_Associative_Array</h4> <?php $car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964); foreach ($car as $x => $y) { echo "$x: $y <br>"; } ?>

Example 4

Result View Example

Document

Document in project

You can Download PDF file.

Reference