PHP Associative Arrays

Created with Sketch.

PHP Associative Arrays

Summary: in this tutorial, you will learn about PHP associative arrays and how to use them effectively.

Introduction to the PHP Associative Arrays

Associative arrays are arrays that allow you to keep track of elements by names rather than by numbers.

Creating associative arrays

To create an associative array, you use the array() construct:

<?php

$html = array();

Code language: HTML, XML (xml)

or the JSON notation syntax:

<?php

$html = [];

Code language: HTML, XML (xml)

Adding elements to an associative array

To add an element to an associative array, you need to specify a key. For example, the following adds the title to the $html array:

<?php

$html['title'] = 'PHP Associative Arrays';
$html['description'] = 'Learn how to use associative arrays in PHP';

print_r($html);

Code language: HTML, XML (xml)

Output:

Array
(
[title] => PHP Associative Arrays
[description] => Learn how to use associative arrays in PHP
)

Code language: PHP (php)

Accessing elements in an associative array

To access an element in an associative array, you use the key. For example, the following shows how to access the element whose key is title in the $html array:

<?php

$html['title'] = 'PHP Associative Arrays';
$html['description'] = 'Learn how to use associative arrays in PHP';

echo $html['title'];

Code language: HTML, XML (xml)

Output:

PHP Associative Arrays

 

Summary

  • Use an associative array when you want to reference elements by names rather than numbers.

Leave a Reply

Your email address will not be published. Required fields are marked *