Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

Associative Arrays

PHP Associative Arrays

Associative arrays are arrays that use custom named keys assigned to their elements.

Example

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
var_dump($car);

Access Associative Arrays

To access an array item, you can refer to its key name.

Example

Show the car’s model:

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
echo $car["model"];

Change Value

To modify the value of an array item, use its key name:

Example

Update the year item:

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
$car["year"] = 2024;
var_dump($car);

Loop Through an Associative Array

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

Example

Output all items in the array, including both keys and values:

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